-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path230. Kth Smallest Element in a BST.java
60 lines (60 loc) · 1.81 KB
/
230. Kth Smallest Element in a BST.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int count = 0;
public int kthSmallest(TreeNode root, int k) {
TreeNode node = kth(root, k);
return node.val;
}
// with Constant Space -- O(1), TC = O(height)
private TreeNode kth(TreeNode root, int k) {
if (root == null) return null;
// faith
TreeNode rl = kth(root.left, k);
if (rl != null) return rl;
this.count++;
if (count == k) return root;
TreeNode rr = kth(root.right, k);
if (rr != null) return rr;
return null;
}
/*
jekono BST te inorder traverse korlei to sorted order pawa jai.
question ta meaning less, but practice concepts of BST
inorder traverse korbo - automatic asc order node pabo,
simply nodes.get(k-1) korlei asha kori hye jabe!
*/
private static ArrayList<Integer> nodes = new ArrayList<>();
public int kthSmallest2(TreeNode root, int k) {
performInOrderTraversal(root);
return nodes.get(k-1); // 0 based indexing
}
private static void performInOrderTraversal(TreeNode root) {
if (root == null) return;
performInOrderTraversal(root.left);
nodes.add(root.val);
performInOrderTraversal(root.right);
}
}