题目描述
给定一棵二叉搜索树,请找出其中的第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 (k <= 0 || pRoot == nullptr) return nullptr;
stack<TreeNode*> s;
while (!s.empty() || pRoot != nullptr){
while (pRoot){
s.emplace(pRoot);
pRoot = pRoot->left;
}
k--;
auto cur = s.top();
s.pop();
if (0 == k) return cur;
if (cur->right) pRoot = cur->right;
}
return nullptr;
}
};
最后
以上就是大力树叶最近收集整理的关于二叉搜索树的第k个结点的全部内容,更多相关二叉搜索树内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复