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 <= 10⁴
0 <= Node.val <= 10⁴
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?
Test Cases
1 2 3 4 5 6 7 8
# 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 classSolution: defkthSmallest(self, root: Optional[TreeNode], k: int) -> int:
import os import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) from _utils.binary_tree import build_tree from solution import Solution
# Definition for a binary tree node. classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
classSolution: defkthSmallest(self, root: Optional[TreeNode], k: int) -> int: i = 0 stack = [] while root or stack: if root: stack.append(root) root = root.left else: root = stack.pop() if (i := i + 1) == k: return root.val root = root.right