题目描述
给定一棵二叉搜索树,请找出其中的第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:
vector<int> nums;
TreeNode* ret;
TreeNode* KthNode(TreeNode* root, int k)
{
ret = NULL;
if(root == NULL || k == 0)
return NULL;
bianli(root);
sort(nums.begin(), nums.end());
int val = nums[k-1];
cal(root, val);
return ret;
}
void bianli(TreeNode* root)
{
if(root != NULL)
{
nums.push_back(root->val);
bianli(root->left);
bianli(root->right);
}
}
void cal(TreeNode* root,int& val)
{
if(root != NULL)
{
if(ret == NULL)
{
if(root->val == val)
{
ret = root;
return;
}
}
else
return;
cal(root->left,val);
cal(root->right,val);
}
}
};