We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent fef44ff commit b66ddaaCopy full SHA for b66ddaa
Medium/Kth Smallest Element in a BST.java
@@ -15,17 +15,21 @@
15
*/
16
class Solution {
17
public int kthSmallest(TreeNode root, int k) {
18
+ Integer result = null;
19
Stack<TreeNode> stack = new Stack<>();
- 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;
+ while (root != null) {
+ stack.push(root);
+ root = root.left;
+ }
+ while (k > 1 && !stack.isEmpty()) {
+ TreeNode removed = stack.pop();
+ TreeNode rightNode = removed.right;
27
+ while (rightNode != null) {
28
+ stack.push(rightNode);
29
+ rightNode = rightNode.left;
30
}
- root = root.right;
31
+ k--;
32
33
+ return stack.peek().val;
34
35
0 commit comments