Skip to content

Commit 8c057be

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 230_Kth_Smallest_Element_in_a_BST.java
1 parent 5cc4816 commit 8c057be

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int kthSmallest(TreeNode root, int k) {
3+
if (root == null) {
4+
return -1;
5+
}
6+
7+
Stack<TreeNode> stack = new Stack<>();
8+
int result = 0;
9+
10+
while (root != null || !stack.isEmpty()) {
11+
while (root != null) {
12+
stack.push(root);
13+
root = root.left;
14+
}
15+
16+
root = stack.pop();
17+
18+
k--;
19+
20+
if (k == 0) {
21+
result = root.val;
22+
break;
23+
}
24+
25+
root = root.right;
26+
}
27+
28+
return result;
29+
}
30+
}

0 commit comments

Comments
 (0)