Skip to content

Commit 26d5020

Browse files
committed
feat: kth-smallest-element-in-a-bst solution
1 parent c94cd08 commit 26d5020

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* val: number
5+
* left: TreeNode | null
6+
* right: TreeNode | null
7+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.left = (left===undefined ? null : left)
10+
* this.right = (right===undefined ? null : right)
11+
* }
12+
* }
13+
*/
14+
/**
15+
* Binary Search Tree ํŠน์„ฑ์„ ๊ณ ๋ คํ•˜์—ฌ k๋ฒˆ์งธ ์ž‘์€ ์ˆซ์ž๋ฅผ ์ฐพ๊ธฐ
16+
* ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ณต์žก๋„
17+
* - ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
18+
* - ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n)
19+
*/
20+
function kthSmallest(root: TreeNode | null, k: number): number {
21+
let count = 0;
22+
let result = 0;
23+
24+
/*
25+
BST์˜ ํŠน์„ฑ
26+
- ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋…ธ๋“œ ๊ฐ’ < ํ˜„์žฌ ๋…ธ๋“œ ๊ฐ’
27+
- ํ˜„์žฌ ๋…ธ๋“œ๊ฐ’ < ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋…ธ๋“œ ๊ฐ’
28+
=> ์ค‘์œ„ ์ˆœํšŒ์‹œ ์˜ค๋ฆ„์ฐจ ์ˆœ ๋ฐฉ๋ฌธ
29+
*/
30+
31+
// ์ค‘์œ„ ์ˆœํšŒ ํ•จ์ˆ˜
32+
function inorder(node: TreeNode | null): void {
33+
if (node === null) return;
34+
inorder(node.left);
35+
36+
count++;
37+
if (count === k) {
38+
result = node.val;
39+
return;
40+
}
41+
42+
inorder(node.right);
43+
}
44+
45+
inorder(root);
46+
return result;
47+
}

0 commit comments

Comments
ย (0)