题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
tips: 使用中序遍历获取二叉搜索树,由大到小的遍历序列。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<TreeNode*> inOrderTravel(TreeNode* pRoot) {
vector<TreeNode*> res;
if(pRoot==NULL) {
return res;
} else {
vector<TreeNode*> leftTree=inOrderTravel(pRoot->left);
vector<TreeNode*> rightTree=inOrderTravel(pRoot->right);
for (int i = 0; i < leftTree.size(); i++)
{
res.push_back(leftTree[i]);
}
res.push_back(pRoot);
for (int i = 0; i < rightTree.size(); i++)
{
res.push_back(rightTree[i]);
}
}
return res;
}
TreeNode* KthNode(TreeNode* pRoot, int k)
{
vector<TreeNode*> inOrderlist= inOrderTravel(pRoot);
if(1<=k&&k<=inOrderlist.size())
return inOrderlist[k-1];
else
return NULL;
}
};