Skip to content

Commit 43ebf23

Browse files
solves kth largest element in bst
1 parent 2bd9edd commit 43ebf23

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@
185185
| 226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree) | [![Java](assets/java.png)](src/InvertBinaryTree.java) [![Python](assets/python.png)](python/invert_binary_tree.py) | |
186186
| 227 | [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii) | [![Java](assets/java.png)](src/BasicCalculatorII.java) | |
187187
| 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii) | [![Java](assets/java.png)](src/MajorityElementII.java) | |
188-
| 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst) | | |
188+
| 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst) | [![Java](assets/java.png)](src/KthSmallestElementInABST.java) | |
189189
| 231 | [Power of Two](https://leetcode.com/problems/power-of-two) | [![Java](assets/java.png)](src/PowerOf2.java) [![Python](assets/python.png)](python/is_power_of_2.py) | |
190190
| 232 | [Implement Queue Using Stacks](https://leetcode.com/problems/implement-queue-using-stacks) | [![Java](assets/java.png)](src/MyQueue.java) [![Python](assets/python.png)](python/implement_queue_using_stacks.py) | |
191191
| 234 | [Palindrome Linked Lists](https://leetcode.com/problems/palindrome-linked-list) | [![Java](assets/java.png)](src/PalindromeLinkedList.java) [![Python](assets/python.png)](python/palindrome_linked_list.py) | |

src/KthSmallestElementInABST.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// https://leetcode.com/problems/kth-smallest-element-in-a-bst
2+
// T: O(k + log(N))
3+
// S: O(log(N))
4+
5+
import java.util.Stack;
6+
7+
public class KthSmallestElementInABST {
8+
public int kthSmallest(TreeNode root, int k) {
9+
final Stack<TreeNode> stack = new Stack<>();
10+
addLeftPathToStack(root, stack);
11+
12+
for (int count = 0 ; !stack.isEmpty() ; ) {
13+
final TreeNode current = stack.pop();
14+
count++;
15+
if (count == k) return current.val;
16+
addLeftPathToStack(current.right, stack);
17+
}
18+
19+
return -1;
20+
}
21+
22+
private void addLeftPathToStack(TreeNode root, Stack<TreeNode> stack) {
23+
if (root == null) return;
24+
stack.push(root);
25+
addLeftPathToStack(root.left, stack);
26+
}
27+
}

0 commit comments

Comments
 (0)