-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKthSmallestElementInABST.java
More file actions
46 lines (37 loc) · 924 Bytes
/
KthSmallestElementInABST.java
File metadata and controls
46 lines (37 loc) · 924 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
37
38
39
40
41
42
43
44
45
46
package binary_tree;
import sun.reflect.generics.tree.Tree;
/**
* @Author: Wenhang Chen
* @Description:
* @Date: Created in 8:57 12/18/2019
* @Modified by:
*/
public class KthSmallestElementInABST {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
int num = 0;
TreeNode target;
// static class StopMsgException extends RuntimeException {
// }
public void getSmallest(TreeNode curNode, int k) {
if (curNode == null) return;
getSmallest(curNode.left, k);
num++;
if (num == k) {
target = curNode;
// 跳出所有递归
// throw new StopMsgException();
}
getSmallest(curNode.right, k);
}
public int kthSmallest(TreeNode root, int k) {
getSmallest(root, k);
return target.val;
}
}