题解 | #二叉搜索树的第k个结点#
二叉搜索树的第k个结点
http://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a
/*
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 0;
stack<TreeNode*> stack;
while(!stack.empty() || pRoot){
if(pRoot){
//当前节点非空则找左孩子
stack.push(pRoot);
pRoot = pRoot->left;
}else{
//为空则出栈一个元素,找该元素的右孩子
pRoot = stack.top();
stack.pop();
if(--k == 0){
return pRoot;
}
pRoot = pRoot->right;
}
}
return NULL;
}
};