博客转载请注明地址:http://blog.csdn.net/SunliyMonkey/article/details/48179133
题目描述
题目地址:https://leetcode.com/problems/kth-smallest-element-in-a-bst/
在一颗二叉排序树当中,寻找第k大的数。
考察点
- 递归
- 树的遍历
陷阱
无
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int ret;
int aim;
void search(TreeNode* x, int &ord){
if(!x || ord >= aim)
return;
search(x->left, ord);
ord++;
if(ord == aim){
ret = x->val;
return;
}
search(x->right, ord);
}
int kthSmallest(TreeNode* root, int k) {
int ord = 0;
aim = k;
search(root, ord);
return ret;
}
};