您的位置:首页 > 编程语言 > Java开发

leetcode-230-二叉搜索树中第K小的元素(kth smallest element in a bst)-java

2018-11-20 11:33 309 查看
版权声明:此文章为许诗宇所写,如需转载,请写下转载文章的地址 https://blog.csdn.net/xushiyu1996818/article/details/84290393

题目及测试

[code]package pid230;

/* 二叉搜索树中第K小的元素

给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。

说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

示例 1:

输入: root = [3,1,4,null,2], k = 1
3
/ \
1   4
\
2
输出: 1

示例 2:

输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3   6
/ \
2   4
/
1
输出: 3

进阶:
如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数?

}*/
public class main {

public static void main(String[] args) {
int[] ito=new int[]{3,9,20,15,7};
int[] ito2=new int[]{9,3,15,20,7};
Object[] x=new Object[]{3,1,4,null,2,null,null};
BinaryTree tree=new BinaryTree(x);
tree.printTree(tree.root);
test(tree.root,1);

}

private static void test(TreeNode ito,int ito2) {
Solution solution = new Solution();
int rtn;
long begin = System.currentTimeMillis();
rtn = solution.kthSmallest(ito,ito2);//执行程序
long end = System.currentTimeMillis();
System.out.println("rtn=" );
System.out.println(rtn);
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}

}

解法1(成功,1ms,极快)

在solution中设置一个变量result,每个方法一旦发现现在第一小的数是自己,则把result=root.val
 kthSmallest2方法,返回这个root下找到了几个数
 同时right=kthSmallest2(root.right,k-left-1);,对右边的节点用k-left-1作为第几小的k

[code]package pid230;

import java.util.LinkedList;
import java.util.List;

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
int result=0;

public int kthSmallest(TreeNode root, int k) {
int left=kthSmallest2(root.left,k);
if(k-left>1){
int right=kthSmallest2(root.right,k-left-1);
}
else{
if(k-left==1){
result=root.val;
}
//left=k或left>k说明left中已经找到result
}
return result;
}
//返回这个root下找到了几个数
public int kthSmallest2(TreeNode root, int k) {
if(root==null){
return 0;
}
if(k<=0){
return 0;
}
int left=kthSmallest2(root.left,k);
int right=0;
if(k-left>1){
right=kthSmallest2(root.right,k-left-1);
}
else{
if(k-left==1){
result=root.val;
}
}
return left+right+1;
}
}

解法2(别人的)

   很有趣的题,但是很简单,实际上就是对树的中序遍历,关于第K小,因为是二叉搜索树,所以最左边的就是最小的,那么中序遍历的情况下,第一次回溯到中序就是最小的一个节点,从该节点开始判定index累加,当index == K的时候,该节点就是第K小了。主要还是考察了二叉搜索树的概念吧。

这个方法就是将k与第几个分开来,让人看得明白

        注意剪枝,适当剪枝能显著提升速度,例如找到第K小以后设置flag,直接结束遍历。
 

[code]class Solution {
public static int index;
public static int ans;
public static int flag;
public static int now;

public static void solve(TreeNode root){
if(root.left != null){
solve(root.left);
}
now++;
if(flag == 1) return;
if(now == index){
flag = 1;
ans = root.val;
return;
}
if(root.right != null){
solve(root.right);
}

}

public int kthSmallest(TreeNode root, int k) {
index = k;
flag = 0;
now = 0;
solve(root);
return ans;
}
}

 

 

 

 

 

 

 

 

 

 

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: