Skip to content

Commit ad9077d

Browse files
Add KthSmallestElementInBST implementation with test
1 parent 0c79d33 commit ad9077d

File tree

4 files changed

+59
-0
lines changed

4 files changed

+59
-0
lines changed

Area.java

Whitespace-only changes.

first-contributions

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Subproject commit d58c69ca9ad0641a155f3a6c95efb484dc0a5abe
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.thealgorithms.datastructures.trees;
2+
3+
/**
4+
* Finds the kth smallest element in a Binary Search Tree.
5+
*
6+
* Time Complexity: O(n)
7+
* Space Complexity: O(h)
8+
*/
9+
public final class KthSmallestElementInBST {
10+
11+
private KthSmallestElementInBST() {
12+
}
13+
14+
public static int kthSmallest(BinaryTree.Node root, int k) {
15+
Counter counter = new Counter();
16+
BinaryTree.Node result = inorder(root, k, counter);
17+
return result != null ? result.data : -1;
18+
}
19+
20+
private static BinaryTree.Node inorder(BinaryTree.Node node, int k, Counter counter) {
21+
if (node == null) {
22+
return null;
23+
}
24+
25+
BinaryTree.Node left = inorder(node.left, k, counter);
26+
if (left != null) {
27+
return left;
28+
}
29+
30+
counter.count++;
31+
if (counter.count == k) {
32+
return node;
33+
}
34+
35+
return inorder(node.right, k, counter);
36+
}
37+
38+
private static class Counter {
39+
int count = 0;
40+
}
41+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.thealgorithms.datastructures.trees;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class KthSmallestElementBSTTest {
8+
9+
@Test
10+
void simpleTest() {
11+
BinaryTree.Node root = new BinaryTree.Node(5);
12+
root.left = new BinaryTree.Node(3);
13+
root.right = new BinaryTree.Node(7);
14+
15+
assertEquals(3, KthSmallestElementInBST.kthSmallest(root, 1));
16+
}
17+
}

0 commit comments

Comments
 (0)