劍指offer 二叉搜索樹的第k個結點

題目描述

給定一顆二叉搜索樹,請找出其中的第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:
    int count=0;
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(pRoot){
        	TreeNode* ret=KthNode(pRoot->left,k);
        	if(ret) return ret;
        	if(++count==k) return pRoot;
        	ret=KthNode(pRoot->right,k);
        	if(ret) return ret;    
        }
			return nullptr;
    }
};







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章