Problem 432977 · medium · Level 04 Non-Linear Data Structures

Rebuild a BST From Its Preorder

binary search tree · recursion · bounds

Given preorder, the preorder traversal of a binary search tree with distinct values (every node's left subtree holds smaller values and its right subtree larger values), rebuild the tree and return its root.

Examples

        9
       / \
      4   15
     / \  /
    2   6 11
       /
      5

Input:  preorder = [9, 4, 2, 6, 5, 15, 11]
Output: tree_to_list(...) == [9, 4, 15, 2, 6, 11, None, None, None, 5]

Input:  preorder = [3, 1, 2]
Output: [3, 1, None, None, 2]

Goals

  • Use BST ordering instead of a second traversal to decide where each value goes
  • Carry an upper bound through the recursion so each value is consumed once
Starting Python…