-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthSmallest.java
More file actions
37 lines (32 loc) · 998 Bytes
/
KthSmallest.java
File metadata and controls
37 lines (32 loc) · 998 Bytes
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
package BinarySearchTrees;
public class KthSmallest {
static int KSmallestUsingMorris(Node root, int k) {
int count = 0;
int kSmall = Integer.MIN_VALUE;
Node curr = root;
// Morris Traversal.
while (curr != null) {
if (curr.left == null) {
count++;
if (count == k) kSmall = curr.val;
curr = curr.right;
} else {
Node pre = curr.left;
while (pre.right != null && pre.right != curr)
pre = pre.right;
if (pre.right == null) {
pre.right = curr;
curr = curr.left;
} else {
pre.right = null;
count++;
if (count == k) kSmall = curr.val;
curr = curr.right;
}
}
}
return kSmall;
}
public static void main(String[] args) {
}
}