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
- Levels in the Org Chart (Easy)
- Mirror the Folder Tree (Easy)
- Twin Backup Check (Easy)
- Exact Budget Trail (Easy)
- Shared Boss in the ID Tree (Easy)
- Floor-by-Floor Roster (Medium)
- Unbeaten on the Way Down (Medium)
- Longest Handoff Chain (Medium)
- Shelf Index Check (Medium)
- K-th Cheapest Price (Medium)
- Closest Shared Folder (Medium)
- Best Relay Route (Hard)
- Downhill Trails With a Target Sum (Hard)
- Office Wi-Fi Repeaters (Hard)