-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathKthSmallestElementinaBST.java
70 lines (52 loc) · 1.74 KB
/
KthSmallestElementinaBST.java
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
64
65
66
67
68
69
70
package problems.medium;
import problems.utils.TreeNode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sherxon on 1/6/17.
*/
public class KthSmallestElementinaBST {
/**
* This is iterative solution with O(N) space and O(N) time.
* get kth element from inorder traversal of Binary search tree.
*/
public int kthSmallest(TreeNode root, int k) {
List<Integer> list = new ArrayList<>();
inOrder(root, list);
return list.get(k - 1);
}
void inOrder(TreeNode root, List<Integer> list) {
if (root == null) return;
inOrder(root.left, list);
list.add(root.val);
inOrder(root.right, list);
}
/**
* Recursive Binary Search method. Time complexity is little higher than previous one but This does not use
* any extra memory. We can use O(N) space in order to keep size of all nodes to make DP solution.
*/
public int kthSmallest2(TreeNode root, int k) {
// int count = nodeCount(root);
// if (k < count)
// return kthSmallest2(root.left, k);
// else if (k > count + 1)
// return kthSmallest2(root.right, k - 1 - count); // 1 is current node
// return root.val;
if (root == null || k < 0) {
return -1;
}
int leftCount = nodeCount(root.left);
if (k == leftCount + 1) {
return root.val;
}
if (k < leftCount + 1) {
return kthSmallest2(root.left, k);
} else {
return kthSmallest2(root.right, k - 1 - leftCount);
}
}
private int nodeCount(TreeNode root) {
if (root == null) return 0;
return nodeCount(root.left) + nodeCount(root.right) + 1;
}
}