题目描述
给定一棵二叉搜索树,请找出其中的第k小的TreeNode结点。
示例1
输入
复制
{5,3,7,2,4,6,8},3
返回值
复制
{4}
说明
按结点数值大小顺序第三小结点的值为4
①我写的需要多一个内存的:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<TreeNode*> res;
TreeNode* KthNode(TreeNode* pRoot, int k) {
if(k==0) return NULL;
inOrder(pRoot);
if(k>res.size()) return NULL;
return res[k-1];
}
void inOrder(TreeNode *pRoot)
{
if(pRoot==NULL) return;
inOrder(pRoot->left);
res.push_back(pRoot);
inOrder(pRoot->right);
}
};
②可以改成count计数不需要额外内存的:
/*
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 *res=NULL;
TreeNode* KthNode(TreeNode* pRoot, int k) {
if(k==0) return NULL;
inOrder(pRoot,k);
return res;
}
void inOrder(TreeNode *pRoot,int k)
{
if(pRoot==NULL) return;
inOrder(pRoot->left,k);
count++;
if(count==k) res=pRoot;
inOrder(pRoot->right,k);
}
};
其实直接在原函数里写递归更简单。但秉持的写作习惯是一般另外写一个inOrder函数来遍历。且一般以void作为返回值。