-
Notifications
You must be signed in to change notification settings - Fork 56
/
Solution.java
55 lines (50 loc) · 1.38 KB
/
Solution.java
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
47
48
49
50
51
52
53
54
55
package g0201_0300.s0230_kth_smallest_element_in_a_bst;
// #Medium #Top_100_Liked_Questions #Depth_First_Search #Tree #Binary_Tree #Binary_Search_Tree
// #Data_Structure_II_Day_17_Tree #Level_2_Day_9_Binary_Search_Tree #Big_O_Time_O(n)_Space_O(n)
// #2022_07_04_Time_1_ms_(78.91%)_Space_45.3_MB_(58.87%)
import com_github_leetcode.TreeNode;
/*
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
private int k;
private int count = 0;
private int val;
public int kthSmallest(TreeNode root, int k) {
this.k = k;
calculate(root);
return val;
}
private void calculate(TreeNode node) {
if (node.left == null && node.right == null) {
count++;
if (count == k) {
this.val = node.val;
}
return;
}
if (node.left != null) {
calculate(node.left);
}
count++;
if (count == k) {
this.val = node.val;
return;
}
if (node.right != null) {
calculate(node.right);
}
}
}