File tree 1 file changed +50
-0
lines changed
kth-smallest-element-in-a-bst
1 file changed +50
-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
+ private TreeNode resultNode = null ;
20
+
21
+ public int kthSmallest (TreeNode root , int k ) {
22
+ searchNode (root , k );
23
+ return resultNode .val ;
24
+ }
25
+
26
+ public void searchNode (TreeNode node , int k ) {
27
+
28
+ if (resultNode != null ) return ;
29
+
30
+ if (node .left != null ) {
31
+ searchNode (node .left , k );
32
+ }
33
+
34
+ count ++;
35
+
36
+ if (count == k ) {
37
+ resultNode = node ;
38
+ return ;
39
+ }
40
+
41
+ if (node .right != null ) {
42
+ searchNode (node .right , k );
43
+ }
44
+ }
45
+ }
46
+
47
+ // n : ๋
ธ๋ ๊ฐ์
48
+ // time : O(n) ์ต์
์ ๊ฒฝ์ฐ ๋ชจ๋ ๋
ธ๋๋ฅผ ํ์ํด์ผํจ
49
+ // space : O(n) ์ต์
์ ๊ฒฝ์ฐ ํ ์ชฝ์ผ๋ก ๋
ธ๋๊ฐ ์น์ฐ์ณ์ ธ ์์
50
+ // -> ์ฌ๊ท ํธ์ถ์ด ์ด๋ฃจ์ด์ง๋ฏ๋ก ์คํ์ ์์ -> ํ ์ชฝ์ผ๋ก ์ ๋ ค ์์ผ๋ฉด ํธ๋ฆฌ์ ๋์ด๊ฐ n์ด ๋จ (ํธ๋ฆฌ์ ์ต๋ ๋์ด๊ฐ ์คํ์ ์ต๋ ๊น)
You canโt perform that action at this time.
0 commit comments