LeetCode/solutions/230. Kth Smallest Element in a BST.md
2019-09-23 22:01:32 +08:00

56 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [230. Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)
# 思路
题意要求返回一棵二叉搜索树中第k大的元素。
## 思路一
二叉搜索树有什么特点二叉搜索树的中序遍历是有序的。因此我们可以用中序遍历解此题我们需要维护一个count初始为k每遍历一个节点count就自减1当count为
0时当前节点即所求。
## 思路二
还可以采取分治的思路即先判断所求节点是在左子树还是右子树。为此我们需要首先得到左子树的节点数left_node_num
* 若`left_node_num == k - 1`即当前root即所求
* 否则,若`left_node_num > k - 1`,即所求节点在左子树,递归进入左子树求解。
* 否则,即所求节点在左子树,递归进入右子树求解。
# C++
## 思路一
``` C++
class Solution {
private:
void inorder(TreeNode *root, int &res, int &count){
if(!root) return;
inorder(root -> left, res, count);
if(!(--count)) res = root -> val; // find it
else inorder(root -> right, res, count);
}
public:
int kthSmallest(TreeNode* root, int k) {
int res = -1;
inorder(root, res, k);
return res;
}
};
```
## 思路二
``` C++
class Solution {
private:
int node_num(TreeNode *root){
if(!root) return 0;
return node_num(root -> left) + node_num(root -> right) + 1;
}
public:
int kthSmallest(TreeNode* root, int k) {
int left_node_num = node_num(root -> left);
if(left_node_num == k - 1) return root -> val;
if(left_node_num > k - 1) return kthSmallest(root -> left, k);
return kthSmallest(root -> right, k - left_node_num - 1);
}
};
```