題目描述:
給定一棵二叉搜索樹,請找出其中的第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:
int index = 0;
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot != NULL)
{
TreeNode* node = KthNode(pRoot->left,k);
if(node != NULL)
return node;
index++;
if(index == k)
return pRoot;
node = KthNode(pRoot->right,k);
if(node != NULL)
return node;
}
return NULL;
}
};