天天看點

Sword To Offer 062 - 二叉搜尋樹的第k個結點二叉搜尋樹的第k個結點

二叉搜尋樹的第k個結點

Desicription

給定一顆二叉搜尋樹,請找出其中的第k大的結點。按結點數值大小順序第三個結點的值為4。

Solution

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
private:
    TreeNode* res = nullptr;
    int currentCount = 0;
    bool foundFLag = false;
    void OnSearch(TreeNode* pRoot, int k) {
        if(!pRoot || foundFLag) {
            return ;
        }
        OnSearch(pRoot->left, k);
        currentCount++;
        if(currentCount == k) {
            res = pRoot;
            foundFLag = true;
            return ;
        }
        OnSearch(pRoot->right, k);
    }
public:
    TreeNode* KthNode(TreeNode* pRoot, int k) {
        OnSearch(pRoot, k);
        return res;
    }
};           

複制