Skip to content
BytePatterns

Rebuild From Two Walks

HardTrees & BST#divide-and-conquer#hash-map#recursion~45m

Problem

You are handed the values of a binary tree in two orders: the walk that visits a node before its subtrees, and the walk that visits the left subtree, then the node, then the right subtree. All values are distinct. Reconstruct the tree those two walks came from and return its root.

Examples

Input:  before = [3, 9, 20, 15, 7], middle = [9, 3, 15, 20, 7]
Output: 3 with left child 9 and right child 20, whose children are 15 and 7
Input:  before = [1, 2], middle = [2, 1]
Output: 1 with a single left child 2
Why:    the middle walk is what reveals the child hangs on the left
Input:  before = [], middle = []
Output: empty
Why:    edge case, two empty walks describe an empty tree

Hints

0 / 3

Stuck on the idea rather than the code? Rebuild From Traversals covers it.