File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
kth-smallest-element-in-a-bst Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * function TreeNode(val, left, right) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.left = (left===undefined ? null : left)
6
+ * this.right = (right===undefined ? null : right)
7
+ * }
8
+ */
9
+ /**
10
+ * @param {TreeNode } root
11
+ * @param {number } k
12
+ * @return {number }
13
+ */
14
+ var kthSmallest = function ( root , k ) {
15
+ const arr = [ ] ;
16
+
17
+ const dfs = ( node ) => {
18
+ arr . push ( node . val ) ;
19
+
20
+ if ( node ?. left ) {
21
+ dfs ( node . left ) ;
22
+ }
23
+
24
+ if ( node ?. right ) {
25
+ dfs ( node . right ) ;
26
+ }
27
+ }
28
+
29
+ dfs ( root ) ;
30
+
31
+ const sort = arr . sort ( ( a , b ) => a - b ) ;
32
+
33
+ return sort [ k - 1 ] ;
34
+ } ;
35
+
36
+ // 시간복잡도 -> O(nlogn) dfs로 노드의 val을 배열에 넣고 정렬하는 시간이 소요됨
37
+ // 공간복잡도 -> O(n) 리스트의 길이만큼 arr의 공간이 필요함
You can’t perform that action at this time.
0 commit comments