题目描述
给定一棵二叉搜索树,请找出其中的第k大的结点。例如, (5,3,7,2,4,6,85,3,7,2,4,6,85,3,7,2,4,6,8) 中,按结点数值大小顺序第三大结点的值为444。
思路:
如上图中的二叉树,我们对其进行中序遍历,得到结果{1,3,4,6,7,8,10,13,141,3,4,6,7,8,10,13,141,3,4,6,7,8,10,13,14},可以发现这个结果就是有序的,那么我们只需进行中序遍历找到第k个节点即为第kkk大节点
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
int cnt = 0;
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if (pRoot != nullptr) {
TreeNode* pNode = KthNode(pRoot->left, k);
//结束底层递归
if (pNode)
return pNode;
cnt++;
if (cnt == k)
return pRoot;
pNode = KthNode(pRoot->right, k);
if (pNode)
return pNode;
}
return nullptr;
}
};