题意
给定一棵二叉搜索树,请找出其中的第k小的结点。
题解
很简单,中序遍历即可,类似的还有这道题剑指Offer系列54—二叉搜索树的第k大节点,将中序遍历反过来,先遍历右子树,再遍历左子树
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
private:
TreeNode* res;
int k;
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
this->k = k;
this->res = nullptr;
inOrder(pRoot);
return res;
}
void inOrder(TreeNode* pRoot){
if(pRoot == nullptr) return;
inOrder(pRoot->left);
if(k == 0) return;
if(--k == 0) res = pRoot;
inOrder(pRoot->right);
}
};