给定一颗二叉搜索树,请找出其中的第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 count = 0;
    
        if(count > k || pRoot == NULL)
            return NULL;
        TreeNode* p = pRoot;
        stack LDRStack;
        TreeNode* kthNode;
        while(p != NULL || !LDRStack.empty()){
            while(p != NULL){
                LDRStack.push(p);
                p = p->left;
            }
            TreeNode* node = LDRStack.top();
            LDRStack.pop();
            count++;
            if(count == k){
                kthNode = node;
            }
            p = node->right;
        }
        return kthNode;
    }

    
};

  

转载于:https://www.cnblogs.com/Czc963239044/p/6978701.html

你可能感兴趣的:(给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。...)