题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
分析
- 其实这就是个中序遍历的变形,因为对于一个二叉搜索树,它最后大小的顺序与中序遍历的遍历顺序是一样的
- 一个公共变量可以在public中定义
- 递归中,return不会结束所有递归,只会返回到上一层调用的地方
- 返回的值的类型需要在函数前定义,和接受返回值的变量类型相同,如此处的TreeNode
答案
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
int count = 0;
TreeNode* np = nullptr;
TreeNode* inOrder(TreeNode* root, int k){
if(root){
np= inOrder(root->left,k);
count++;
if(count == k){
return root;
}
np = inOrder(root->right,k);
}
return np;
}
TreeNode* KthNode(TreeNode* pRoot, int k)
{
TreeNode* ans = inOrder(pRoot,k);
return ans;
}
};