File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
kth-smallest-element-in-a-bst Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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,
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+ }
You can’t perform that action at this time.
0 commit comments