← DiffPush

Construct Binary Tree from Preorder and Inorder Traversal

DiffPush Tier Binary Trees · Hard O(n) · O(n)

Rebuilding the Supply Route Blueprint

A logistics planner lost the org chart of a distribution tree but kept two audit logs: a hub-first walk (each hub recorded before its branches) and a left-first walk (each branch recorded before its hub). Because no two hubs share a name, the two logs together pin down every split point, and the blueprint can be rebuilt exactly.

Input: Two integer arrays — preorder (root, left subtree, right subtree) and inorder (left subtree, root, right subtree) of the same tree. Values are unique.

Output: Return the constructed binary tree serialized as a level-order array (null marks a missing child, trailing nulls trimmed).

Constraints

Examples

Example 1

Input: {"preorder":[3,9,20,15,7],"inorder":[9,3,15,20,7]}
Output: [3,9,20,null,null,15,7]
3 roots the tree; 9 is its lone left child, and 20 heads the right subtree over 15 and 7.

Example 2

Input: {"preorder":[1,2,3],"inorder":[2,1,3]}
Output: [1,2,3]
1 is the root, 2 its left child, 3 its right child.

Solve this in your browser →

Also on LeetCode ↗