题目描述:
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
样例:

分析:
对二叉搜索树进行中序遍历,将遍历后的结果存到数组中,数组中的第k个元素就是二叉搜索树的第k小元素,因为二叉搜索树中序遍历后得到的结果就是得到的结果就是按递增排序的。
int index=0;
int re=-1;
public int kthSmallest(TreeNode root, int k) {
if(root!=null&&index!=k) {
kthSmallest(root.left,k);
index++;
if(index==k) {
re=root.val;
return re;
}
kthSmallest(root.right,k);
}
return re;
}
public int kthSmallest2(TreeNode root, int k) {
int num = count(root.left);
if(num >= k){//大于k,说明第k个节点在左子树中
return kthSmallest2(root.left, k);
}else if(num + 1 < k){
return kthSmallest2(root.right, k-num-1);
}
return root.val;
}
private int count(TreeNode root){
if(root == null){
return 0;
}
return 1 + count(root.left) + count(root.right);
}
相关题目:二叉树的最大深度
public int maxDepth1(TreeNode root) {
if(root==null)
return 0;
int left=maxDepth1(root.left);
int right=maxDepth1(root.right);
if(left>right)
return left+1;
else
return right+1;
}

博客围绕给定的二叉搜索树,要编写函数查找第k个最小元素。假设k有效,范围在1到二叉搜索树元素个数之间。分析指出对二叉搜索树进行中序遍历,将结果存数组,数组第k个元素即所求,还提及相关题目二叉树最大深度。
1106

被折叠的 条评论
为什么被折叠?



