Skip to content

Commit 172f4fd

Browse files
committed
feat: kth-smallest-element-in-a-bst
1 parent fe056ca commit 172f4fd

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/kth-smallest-element-in-a-bst/">week13-3. kth-smallest-element-in-a-bst</a>
3+
* <li>Description: Given the root of a binary search tree, and an integer k, return the kth smallest value</li>
4+
* <li>Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree</li>
5+
* <li>Time Complexity: O(N), Runtime 0ms </li>
6+
* <li>Space Complexity: O(H), Memory 44.5MB</li>
7+
* <li>Note: If the BST is modified often (with frequent insertions or deletions), consider using an Augmented BST, Segment Tree, or TreeMap with additional metadata to efficiently support dynamic updates and k-th smallest queries in logarithmic time. </li>
8+
*/
9+
class Solution {
10+
public int kthSmallest(TreeNode root, int k) {
11+
return inorder(root, new AtomicInteger(k));
12+
}
13+
14+
public Integer inorder(TreeNode node, AtomicInteger k) {
15+
if (node == null) {
16+
return null;
17+
}
18+
19+
Integer value = inorder(node.left, k);
20+
if (value != null) {
21+
return value;
22+
}
23+
24+
if (k.decrementAndGet() == 0) {
25+
return node.val;
26+
}
27+
28+
return inorder(node.right, k);
29+
}
30+
31+
}

0 commit comments

Comments
 (0)