题目描述
给定一棵二叉搜索树,请找出其中的第k小的TreeNode结点。
思路
思路1:
最直接的,我们知道将一棵二叉搜索树进行中序遍历,得到的结果就是升序排列的,这样就能轻松找到了。
实现:
class Solution {
public:
vector<TreeNode*> v;
void dfs(TreeNode* p)//中序遍历
{
if (!p) return;
dfs(p->left);
v.push_back(p);
dfs(p->right);
}
TreeNode* KthNode(TreeNode* pRoot, int k) {
dfs(pRoot);
if (k>v.size()||k<=0) return nullptr;//边界条件
return v[k-1];
}
};
仔细想想上面的实现,不管查找哪个数字,都要将整个二叉树遍历完才能找到,并且还需要额外开辟一个O(n)的空间来存储遍历结果。
class Solution {
public:
TreeNode* ret=nullptr;
int count=0;//记录第几小了
void dfs(TreeNode* p,const int &k)
{
if (!p) return;
if (count<k) dfs(p->left,k);
count++;//每次左边递归返回就要++
if (count==k)
{
ret=p;
}
if (count<k) dfs(p->right,k);
}
TreeNode* KthNode(TreeNode* pRoot, int k) {
if (k<=0) return nullptr;
dfs(pRoot,k);
return ret;
}
};