二叉搜索树的第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: TreeNode* KthNode(TreeNode* pRoot, int k) { if(!pRoot || k ==0){ return NULL; } //中序遍历 stack<TreeNode*> stack; int index = 0; TreeNode *p = pRoot; TreeNode *res = NULL; while(p || !stack.empty()){ while(p){ stack.push(p); p = p->left; } if(!stack.empty()){ p = stack.top(); stack.pop(); index ++; if(index == k) { res = p; break; } else p = p->right; } } return res; } };