알고리즘 문제/Leetcode
230. Kth Smallest Element in a BST
BEstyle
2023. 1. 23. 22:32
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Constraints:
- The number of nodes in the tree is n.
- 1 <= k <= n <= 104
- 0 <= Node.val <= 104
Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
#
'''
1. 아이디어 :
1) BFS, DFS로 풀 수 있지만, BFS로 스택을 만들고, 왼쪽이 아닌 오른쪽부터 빼게되면, 순서대로 빠지기 때문에
BST에서 쓰기 좋다.
2. 시간복잡도 :
1) O(n)
3. 자료구조 :
1) 이진트리
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
n = 0
stack = []
cur = root
while cur or stack:
while cur:
stack.append(cur)
cur=cur.left
cur = stack.pop()
print(cur.val)
n+=1
if n==k:
return cur.val
cur = cur.right