Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added Area.java
Empty file.
1 change: 1 addition & 0 deletions first-contributions
Submodule first-contributions added at d58c69
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.thealgorithms.datastructures.trees;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class KthSmallestElementBSTTest {

@Test
void simpleTest() {
BinaryTree.Node root = new BinaryTree.Node(5);
root.left = new BinaryTree.Node(3);
root.right = new BinaryTree.Node(7);

assertEquals(3, KthSmallestElementInBST.kthSmallest(root, 1));
}
}
Loading