题目及测试
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
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,直接结束遍历。
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;
}
}
解法3(成功,2ms,很快)
通过循环的方式进行中序遍历,得到k变为1时,返回节点的val
public int kthSmallest(TreeNode root, int k) {
LinkedList<TreeNode> stack=new LinkedList<>();
TreeNode current=root;
while(current!=null||!stack.isEmpty()){
while(current!=null){
stack.push(current);
current=current.left;
}
//此处current为null,上一步加入的current是最左边的node
current=stack.pop();
if(k==1){
return current.val;
}else{
k--; // 遍历到一个节点
}
current=current.right;
}
return 0;
}