题目描述
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / 3 7 / / 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)//中序遍历
{
int cnt = 0;
return KthNode(pRoot, k, cnt);
}
TreeNode* KthNode(TreeNode* pRoot, int k, int &cnt)
{
if (pRoot == NULL) {
return NULL;
}
TreeNode* left = KthNode(pRoot->left, k, cnt);
if (left != NULL) {
return left;
}
++cnt;
if (cnt == k) {
return pRoot;
}
return KthNode(pRoot->right, k, cnt);
}
};