Rebuild the Bracket

Medium · Trees & BSTs · about 25 min

A tournament bracket (a binary tree with distinct team ids) was lost, but two logs survived:

  • preorder: each match visited as node, then its left side, then its right side.
  • inorder: left side, then node, then right side.

Rebuild the tree and return it as a level-order list: the root first, then each node's left and right child in turn, None / null for a missing child, with any None / null at the very end removed. The starter has a TreeNode class and a to_level(root) helper that does that conversion. Empty logs give [].

  • Both lists have the same length, up to 3,000, and always describe one valid tree.

Examples:

rebuild_bracket([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]) → [3, 9, 20, None, None, 15, 7]

rebuild_bracket([1, 2], [1, 2]) → [1, None, 2]

Hints

  • Which log tells you the root right away?
  • Find that root in the inorder log. What is to its left, and what is to its right?
  • Preorder lists the whole left side before the right side, so build the left subtree first. A dictionary of inorder positions avoids searching again and again.

Learn the pattern first: the Trees & BSTs lesson.

More Trees & BSTs problems