-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthSmallestElementinaBST.java
More file actions
72 lines (62 loc) · 1.64 KB
/
Copy pathKthSmallestElementinaBST.java
File metadata and controls
72 lines (62 loc) · 1.64 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
64
65
66
67
68
69
70
71
72
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
TreeNode t = ksh(root, k);
return t.val;
}
private int cnt = 0;
private TreeNode ksh(TreeNode root, int k) {
if(root == null) return null;
TreeNode t = ksh(root.left, k);
if(t != null) return t;
cnt++;
if(cnt == k) return root;
return ksh(root.right, k);
}
}
// Solution#2
class Solution {
public int kthSmallest(TreeNode root, int k) {
if(root == null) throw new IllegalArgumentException("x");
Deque<TreeNode> st = new ArrayDeque<>();
while(root != null || !st.isEmpty()) {
if(root != null) {
st.push(root);
root = root.left;
}else{
TreeNode t = st.pop();
k--;
if(k == 0) return t.val;
root = t.right;
}
}
throw new IllegalArgumentException("x");
}
}
//Solution#3 Recursive version of Solution #2
class Solution {
public int kthSmallest(TreeNode root, int k) {
inorder(root, k);
return result;
}
private int cnt = 0;
private int result = 0;
private void inorder(TreeNode root, int k) {
if(root == null) return;
inorder(root.left, k);
cnt++;
if(cnt == k) {
result = root.val;
return;
}
inorder(root.right, k);
}
}