File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
kth-smallest-element-in-a-bst Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 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
You canโt perform that action at this time.
0 commit comments