Skip to content

Commit 6b4cf59

Browse files
committed
solve kth smallest element in a bst
1 parent 1aa0cf7 commit 6b4cf59

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
public class Solution {
2+
private int count = 0;
3+
private int answer = -1;
4+
5+
public int kthSmallest(TreeNode root, int k) {
6+
ordering(root, k);
7+
return answer;
8+
}
9+
10+
private void ordering(TreeNode node, int k) {
11+
if (node == null) return;
12+
ordering(node.left, k);
13+
count++;
14+
if (count == k) {
15+
answer = node.val;
16+
return;
17+
}
18+
ordering(node.right, k);
19+
}
20+
}

0 commit comments

Comments
 (0)