forked from JsonChao/Awesome-Algorithm-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution230.java
More file actions
36 lines (29 loc) · 746 Bytes
/
Copy pathSolution230.java
File metadata and controls
36 lines (29 loc) · 746 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package binary_search_tree_problem;
public class Solution230 {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
private int cnt = 0;
private int val;
public int kthSmallest(TreeNode root, int k) {
inOrder(root, k);
return val;
}
private void inOrder(TreeNode root, int k) {
if (root == null) {
return;
}
// 1、遍历到左边,由最小的值开始
inOrder(root.left, k);
cnt++;
if (cnt == k) {
val = root.val;
return;
}
// 2、然后遍历右边,得到次小的值
inOrder(root.right, k);
}
}