-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthSmallBST.java
More file actions
63 lines (40 loc) · 1.17 KB
/
Copy pathKthSmallBST.java
File metadata and controls
63 lines (40 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package trees;
public class KthSmallBST {
static int pos=0;
public static int kthSmallestNode(BinaryTreeNode<Integer> root,int K){
if(root==null){
return Integer.MIN_VALUE;
}
int leftsmallest=kthSmallestNode(root.left,K);
if(leftsmallest!=Integer.MIN_VALUE){
return leftsmallest;
}
pos++;
if(pos==K){
return root.data;
}
return kthSmallestNode(root.right,K);
}
//another way
public static int countallnodes(BinaryTreeNode<Integer> root){
if(root==null){
return 0;
}
return 1+countallnodes(root.left)+countallnodes(root.right);
}
public static int kthSmallestNode2(BinaryTreeNode<Integer> root,int K){
if(root==null){
return Integer.MIN_VALUE;
}
int leftsmallest=countallnodes(root.left);
if(leftsmallest>=K){
return kthSmallestNode2(root.left,K);
}
else if(leftsmallest==K-1){
return root.data;
}
else {
return kthSmallestNode(root.right, K-leftsmallest-1);
}
}
}