Skip to content

Commit 04bdf43

Browse files
authored
[ PS ] : Kth Smallest Element in a BST
1 parent 287c045 commit 04bdf43

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
const kthSmallest = function (root, k) {
15+
const sorted = [];
16+
17+
const traverse = function (root) {
18+
if (!root) return;
19+
traverse(root.left);
20+
sorted.push(root.val);
21+
traverse(root.right);
22+
}
23+
24+
traverse(root);
25+
return sorted[k - 1];
26+
};
27+
28+
// 시간복잡도: O(n)
29+
// 공간복잡도: O(n) (배열)

0 commit comments

Comments
 (0)