|
| 1 | +# https://leetcode.com/problems/kth-smallest-element-in-a-bst/ |
| 2 | + |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +# Definition for a binary tree node. |
| 6 | +class TreeNode: |
| 7 | + def __init__(self, val=0, left=None, right=None): |
| 8 | + self.val = val |
| 9 | + self.left = left |
| 10 | + self.right = right |
| 11 | + |
| 12 | +class Solution: |
| 13 | + def kthSmallest_recur(self, root: Optional[TreeNode], k: int) -> int: |
| 14 | + """ |
| 15 | + [Complexity] |
| 16 | + - TC: O(k) |
| 17 | + - SC: O(height) (call stack) |
| 18 | +
|
| 19 | + [Approach] |
| 20 | + BST를 inorder로 순회하면 오름차순으로 node를 방문할 수 있다. (recursive) |
| 21 | + 각 호출에서 cnt를 세며 k와 같을 때 res 값을 기록한다. |
| 22 | + """ |
| 23 | + cnt, res = 0, None |
| 24 | + |
| 25 | + def inorder(node): |
| 26 | + nonlocal cnt, res |
| 27 | + |
| 28 | + # base condition |
| 29 | + if not node or res: |
| 30 | + return |
| 31 | + |
| 32 | + # recur |
| 33 | + inorder(node.left) |
| 34 | + cnt += 1 |
| 35 | + if cnt == k: |
| 36 | + res = node.val |
| 37 | + inorder(node.right) |
| 38 | + |
| 39 | + inorder(root) |
| 40 | + |
| 41 | + return res |
| 42 | + |
| 43 | + def kthSmallest_recur2(self, root: Optional[TreeNode], k: int) -> int: |
| 44 | + """ |
| 45 | + [Complexity] |
| 46 | + - TC: O(k) |
| 47 | + - SC: O(height) (call stack) |
| 48 | +
|
| 49 | + [Approach] |
| 50 | + 이전 recursive 풀이를 generator 방식으로 바꿀 수 있다. (yield from으로 recursion 구현) |
| 51 | + """ |
| 52 | + |
| 53 | + def inorder(node): |
| 54 | + if node: |
| 55 | + yield from inorder(node.left) |
| 56 | + yield node |
| 57 | + yield from inorder(node.right) |
| 58 | + |
| 59 | + for i, node in enumerate(inorder(root), start=1): |
| 60 | + if i == k: |
| 61 | + return node.val |
| 62 | + |
| 63 | + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: |
| 64 | + """ |
| 65 | + [Complexity] |
| 66 | + - TC: O(k) |
| 67 | + - SC: O(height) (stack에는 최대 height 개의 node가 들어감) |
| 68 | +
|
| 69 | + [Approach] |
| 70 | + BST의 inorder 순회를 stack을 이용하여 iterative 하게 풀이할 수 있다. |
| 71 | + """ |
| 72 | + cnt, stack = 0, [] |
| 73 | + |
| 74 | + # root에서부터 left child를 stack에 넣기 |
| 75 | + while root: |
| 76 | + stack.append(root) |
| 77 | + root = root.left |
| 78 | + |
| 79 | + # leaf left child 부터 stack에서 pop |
| 80 | + while stack: |
| 81 | + node = stack.pop() |
| 82 | + cnt += 1 |
| 83 | + |
| 84 | + if cnt == k: |
| 85 | + return node.val |
| 86 | + |
| 87 | + # 현재 node의 right child가 있다면 stack에 넣고 |
| 88 | + right = node.right |
| 89 | + while right: |
| 90 | + # right child에서부터 left child를 stack에 넣기 |
| 91 | + stack.append(right) |
| 92 | + right = right.left |
0 commit comments