Skip to content

Commit 4d5a551

Browse files
committed
kth-smallest-element-in-a-bst solution
1 parent a2ec0d6 commit 4d5a551

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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의 공간이 필요함

0 commit comments

Comments
 (0)