K-th smallest in BST
Problem
Given theroot
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.Solution
- In-order traversal. Recursive or Iterative.
- Recursive is easy but need to traverse entire tree Or add a lot of ugly code.
- Iterative is tricky.
- Two while loops. One always slides to the left.
- The root is like a pointer.
- It does not always come from the stack!
# Iterative
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stack = []
while True:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
if k == 0:
return root.val
root = root.right
def kthSmallest(self, root, k):
def inorder(r):
return inorder(r.left) + [r.val] + inorder(r.right) if r else []
return inorder(root)[k - 1]
Comments
Post a Comment