題目
【給定一棵二叉搜索樹,請找出其中的第k小的結點。例如, (5,3,7,2,4,6,8) 中,按結點數值大小順序第三小結點的值爲4】
1、分析
二叉搜索樹的左子樹都小於根節點,右子樹都大於根節點。
且其中序遍歷剛好是由大到小的順序,所以用中序遍歷來對二叉搜索樹進行遍歷,同時統計第k大的節點
2、代碼
/*
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)
{
if(pRoot==nullptr || k<1)
return nullptr;
return FindKthNode(pRoot,k);
}
TreeNode* FindKthNode(TreeNode* pRoot,int &k)
{
TreeNode *target=nullptr;
if(pRoot->left!=nullptr)
target=FindKthNode(pRoot->left,k);
if(target==nullptr)
{
if(k==1)
return pRoot;
k--;
}
if( target==nullptr && pRoot->right!=nullptr)
{
target=FindKthNode(pRoot->right,k);
}
return target;
}
};