File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
kth-smallest-element-in-a-bst Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * public class TreeNode {
4
+ * int val;
5
+ * TreeNode left;
6
+ * TreeNode right;
7
+ * TreeNode() {}
8
+ * TreeNode(int val) { this.val = val; }
9
+ * TreeNode(int val, TreeNode left, TreeNode right) {
10
+ * this.val = val;
11
+ * this.left = left;
12
+ * this.right = right;
13
+ * }
14
+ * }
15
+ */
16
+ class Solution {
17
+
18
+ private int count = 0 ;
19
+
20
+ private int kthSmallValue = 0 ;
21
+
22
+ // 시간복잡도: O(k) (불균형 상태의 이진 트리일 경우 O(n))
23
+ public int kthSmallest (TreeNode root , int k ) {
24
+ orderSearch (root , k );
25
+ return kthSmallValue ;
26
+ }
27
+
28
+ // In Order Search
29
+ private void orderSearch (TreeNode node , int k ) {
30
+
31
+ if (node == null ) {
32
+ return ;
33
+ }
34
+
35
+ // HINT => utilize the property of a BST => 좌측 리프 노드부터 탐색
36
+ orderSearch (node .left , k );
37
+
38
+ count ++;
39
+
40
+ if (count == k ) {
41
+ kthSmallValue = node .val ;
42
+ return ;
43
+ }
44
+
45
+ // search right side
46
+ orderSearch (node .right , k );
47
+
48
+ }
49
+
50
+ }
51
+
You can’t perform that action at this time.
0 commit comments