Skip to content

Commit 000f4a6

Browse files
committed
solve: Kth Smallest Element in a BST
1 parent f9b004f commit 000f4a6

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
Constraints:
3+
- The number of nodes in the tree is n.
4+
- 1 <= k <= n <= 10^4
5+
- 0 <= Node.val <= 10^4
6+
7+
Time Complexity: O(n)
8+
- ์ตœ์•…์˜ ๊ฒฝ์šฐ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ
9+
10+
Space Complexity: O(h)
11+
- ์—ฌ๊ธฐ์„œ h๋Š” ํŠธ๋ฆฌ์˜ ๋†’์ด, ์Šคํƒ์— ์ตœ๋Œ€ h๊ฐœ์˜ ๋…ธ๋“œ๊ฐ€ ์ €์žฅ๋จ
12+
13+
ํ’€์ด๋ฐฉ๋ฒ•:
14+
1. ์ค‘์œ„ ์ˆœํšŒ(in-order)๋ฅผ ํ™œ์šฉํ•˜์—ฌ BST์˜ ๋…ธ๋“œ๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋ฐฉ๋ฌธ
15+
2. ์Šคํƒ์„ ํ™œ์šฉ:
16+
- ํŠธ๋ฆฌ์˜ ์™ผ์ชฝ์œผ๋กœ ๋‚ด๋ ค๊ฐ€๋ฉด์„œ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ์Šคํƒ์— ์ €์žฅ
17+
- ์Šคํƒ์—์„œ ๋…ธ๋“œ๋ฅผ ๊บผ๋‚ด๊ณ  ์นด์šดํŠธ ์ฆ๊ฐ€
18+
- k๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ์ฐพ์œผ๋ฉด ํ•ด๋‹น ๊ฐ’์„ ๋ฐ˜ํ™˜
19+
- ์˜ค๋ฅธ์ชฝ ํŠธ๋ฆฌ์— ๋Œ€ํ•ด์„œ ์ด ๊ณผ์ •์„ ๋ฐ˜๋ณต
20+
3. ์ค‘์œ„ ์ˆœํšŒ ์‹œ ๋…ธ๋“œ ๊ฐ’์„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋ฐฉ๋ฌธํ•˜๋ฏ€๋กœ, k๋ฒˆ์งธ๋กœ ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๊ฐ€ k๋ฒˆ์งธ ์ž‘์€ ๊ฐ’
21+
"""
22+
# Definition for a binary tree node.
23+
# class TreeNode:
24+
# def __init__(self, val=0, left=None, right=None):
25+
# self.val = val
26+
# self.left = left
27+
# self.right = right
28+
class Solution:
29+
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
30+
stack = []
31+
node = root
32+
count = 0
33+
34+
while node or stack:
35+
36+
while node:
37+
stack.append(node)
38+
node = node.left
39+
40+
node = stack.pop()
41+
count += 1
42+
43+
if count == k:
44+
return node.val
45+
46+
node = node.right

0 commit comments

Comments
ย (0)