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)