给定一颗二叉搜索树,请找出其中的第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<TreeNode*> 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;
    }

    
};

  

posted @ 2017-06-10 14:38  czcColud  阅读(479)  评论(0编辑  收藏  举报