K-th smallest in BST

 

Problem

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.

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

         



# Recursive

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

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break