forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthSmallestElementInBST.java
More file actions
41 lines (33 loc) · 984 Bytes
/
KthSmallestElementInBST.java
File metadata and controls
41 lines (33 loc) · 984 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
38
39
40
41
package com.thealgorithms.datastructures.trees;
/**
* Finds the kth smallest element in a Binary Search Tree.
*
* Time Complexity: O(n)
* Space Complexity: O(h)
*/
public final class KthSmallestElementInBST {
private KthSmallestElementInBST() {
}
public static int kthSmallest(BinaryTree.Node root, int k) {
Counter counter = new Counter();
BinaryTree.Node result = inorder(root, k, counter);
return result != null ? result.data : -1;
}
private static BinaryTree.Node inorder(BinaryTree.Node node, int k, Counter counter) {
if (node == null) {
return null;
}
BinaryTree.Node left = inorder(node.left, k, counter);
if (left != null) {
return left;
}
counter.count++;
if (counter.count == k) {
return node;
}
return inorder(node.right, k, counter);
}
private static class Counter {
int count = 0;
}
}