Skip to content

Commit b66ddaa

Browse files
authored
Update Kth Smallest Element in a BST.java
1 parent fef44ff commit b66ddaa

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

Medium/Kth Smallest Element in a BST.java

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,21 @@
1515
*/
1616
class Solution {
1717
public int kthSmallest(TreeNode root, int k) {
18+
Integer result = null;
1819
Stack<TreeNode> stack = new Stack<>();
19-
while (true) {
20-
while (root != null) {
21-
stack.push(root);
22-
root = root.left;
23-
}
24-
root = stack.pop();
25-
if (--k == 0) {
26-
return root.val;
20+
while (root != null) {
21+
stack.push(root);
22+
root = root.left;
23+
}
24+
while (k > 1 && !stack.isEmpty()) {
25+
TreeNode removed = stack.pop();
26+
TreeNode rightNode = removed.right;
27+
while (rightNode != null) {
28+
stack.push(rightNode);
29+
rightNode = rightNode.left;
2730
}
28-
root = root.right;
31+
k--;
2932
}
33+
return stack.peek().val;
3034
}
3135
}

0 commit comments

Comments
 (0)