Skip to content

Commit caf0768

Browse files
committed
add solution: kth-smallest-element-in-a-bst
1 parent 2f782a8 commit caf0768

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
'''
2+
# 230. Kth Smallest Element in a BST
3+
4+
BST์—์„œ k ๋ฒˆ์งธ์˜ ๊ฐ’ ์ฐพ๊ธฐ
5+
6+
- Inorder Traversal: ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ๋ฅผ ์ค‘์œ„ ์ˆœํšŒํ•˜๋ฉด ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๊ฐ’์„ ์˜ค๋ฆ„ ์ฐจ์ˆœ์œผ๋กœ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋‹ค.
7+
- ์ค‘์œ„ ์ˆœํšŒ: ์™ผ์ชฝ ์ž์‹ -> ๋ฃจํŠธ -> ์˜ค๋ฅธ์ชฝ ์ž์‹
8+
- k๋ฒˆ์งธ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ๊ตฌํ•˜๋ฉด ๋ฐฉ๋ฌธ์„ ์ค‘๋‹จํ•œ๋‹ค.
9+
'''
10+
class Solution:
11+
'''
12+
## 1. count๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ k๋ฒˆ์งธ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ์ฐพ๋Š” ๋ฐฉ๋ฒ•
13+
- ์ค‘์œ„ ์ˆœํšŒ๋ฅผ ํ•˜๋ฉด์„œ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•˜๊ณ , ๋ฐฉ๋ฌธํ•œ ํšŸ์ˆ˜๋ฅผ ์„ธ์„œ k๋ฒˆ์งธ ๊ฐ’์„ ์ฐพ์Šต๋‹ˆ๋‹ค.
14+
- ์ˆœํšŒ๋ฅผ ์ค‘๋‹จํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์ ˆ์•ฝํ•ฉ๋‹ˆ๋‹ค.
15+
TC: O(n)
16+
SC: O(h) - ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ ๊ณต๊ฐ„ (h๋Š” ํŠธ๋ฆฌ์˜ ๋†’์ด)
17+
'''
18+
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
19+
count = 0
20+
result = None
21+
22+
def inorder(node):
23+
nonlocal count, result
24+
25+
if not node:
26+
return
27+
28+
inorder(node.left)
29+
30+
count += 1
31+
if count == k:
32+
result = node.val
33+
return
34+
35+
inorder(node.right)
36+
37+
inorder(root)
38+
39+
return result
40+
41+
'''
42+
## 2. ์ˆœํšŒ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅํ•˜์—ฌ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ์ฐพ๋Š” ๋ฐฉ๋ฒ•
43+
- ์ˆœํšŒ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅํ•˜์—ฌ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ์ฐพ์Šต๋‹ˆ๋‹ค.
44+
- ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ๋” ๋งŽ์ด ์‚ฌ์šฉํ•˜์ง€๋งŒ, ์ฝ”๋“œ๊ฐ€ ๋” ๊ฐ„๊ฒฐํ•ฉ๋‹ˆ๋‹ค.
45+
TC: O(n)
46+
SC: O(n)
47+
'''
48+
def kthSmallestWithResultList(self, root: Optional[TreeNode], k: int) -> int:
49+
result = []
50+
51+
def inorder(node):
52+
if not node:
53+
return
54+
if len(result) > k:
55+
return node
56+
57+
inorder(node.left)
58+
result.append(node.val)
59+
inorder(node.right)
60+
61+
inorder(root)
62+
63+
return result[k - 1]

0 commit comments

Comments
ย (0)