LeetCode230二叉搜索树中第K小的元素

题目链接

https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/

题解

  • 递归解法
  • 根据BST的性质,中序遍历BST得到的结点序列为结点的升序序列,序列中第k个元素就是第k小的元素。
  • 所以可以中序遍历BST生成升序序列,找到第k个元素则停止遍历。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Problem: LeetCode 230
// URL: https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
// Tags: Tree BST Recursion DFS
// Difficulty: Medium

#include <vector>
using namespace std;

struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
};

class Solution{
private:
vector<int> vals;
int k;
public:
// 中序遍历
void inorder(TreeNode* root){
if (root==nullptr) return;
// 遍历左子树
inorder(root->left);
// 剪枝:如果已经遍历到第K个元素,则不用再遍历
if (this->vals.size() >= this->k) return;
// 遍历当前根结点
this->vals.push_back(root->val);
// 遍历右子树
inorder(root->right);
}

// 获取BST中第k小的元素
int kthSmallest(TreeNode* root, int k) {
this->k = k;
// 中序遍历生成元素的升序序列
inorder(root);
// 结果为升序序列中的第k个元素,下面的两行代码都可以
return this->vals[k - 1]; // return this->vals.back();
}
};

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!