题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
解题思路:
考察的是中序遍历二叉树,中序遍历即为二叉搜索树的顺序。
解题代码:
解法一
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot==nullptr || k==0)
return nullptr;
return KthNodeCore(pRoot,k);
}
private:
TreeNode* KthNodeCore(TreeNode* pRoot, int& k) //中序遍历即为顺序遍历二叉搜索树
{
TreeNode* target=nullptr; //新建一个指针变量用来保存目标节点
if(pRoot->left!=nullptr)
target=KthNodeCore(pRoot->left,k);
if(target==nullptr)
{
if(k==1)
target=pRoot;
k--;
}
if(target==nullptr && pRoot->right!=nullptr)
target=KthNodeCore(pRoot->right,k);
return target;
}
};
解法二 建一个vect保存遍历的节点。遍历到第K个几点就返回
链接:https://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a
来源:牛客网
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
//中序遍历的结果就是有序序列,第K个元素就是vec[K-1]存储的节点指针;
TreeNode* KthNode(TreeNode* pRoot, unsigned int k)
{
if(pRoot==NULL||k<=0) return NULL;
vector<TreeNode*> vec;
Inorder(pRoot,vec);
if(k>vec.size())
return NULL;
return vec[k-1];
}
//中序遍历,将节点依次压入vector中
void Inorder(TreeNode* pRoot,vector<TreeNode*>& vec)
{
if(pRoot==NULL) return;
Inorder(pRoot->left,vec);
vec.push_back(pRoot);
Inorder(pRoot->right,vec);
}
};