题解 | #二叉搜索树的第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:
int j = 0;
TreeNode* temp;
TreeNode* KthNode(TreeNode* pRoot, int k) {
TreeNode* res = pRoot;
if(!pRoot || k == 0)
return nullptr;
if(pRoot->left) {
KthNode(pRoot->left, k);
}
j++;
if(j == k) {
temp = res;
}
if(pRoot->right) {
KthNode(pRoot->right, k);
}
return j < k ? nullptr : temp;
}
};