问题
思路
对于BST而言,最常见的遍历就是中序。因为可以递增序列,此时拿到第k个就可以了。
代码
/*
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 < 1) return NULL;
int cnt = 0;
stack<TreeNode*> stk;
while(pRoot || !stk.empty()){
while(pRoot){
stk.push(pRoot);
pRoot = pRoot->left;
}
if(!stk.empty()){
pRoot = stk.top();
stk.pop();
++cnt;
if( cnt == k ) return pRoot;
pRoot = pRoot->right;
}
}
return NULL;
}
};