← DiffPush

Construct Binary Tree from Inorder and Postorder Traversal

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

Rewinding the Warehouse Shutdown Log

A shutdown audit captured two walks of a conveyor tree: a leaves-first log (each junction written after everything beneath it) and a left-first inventory. Junction names never repeat, so reading the leaves-first log backwards always names the next junction, and the left-first inventory reveals exactly how many conveyors feed each side of it.

Input: Two integer arrays — inorder (left subtree, root, right subtree) and postorder (left subtree, right subtree, root) 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: {"inorder":[9,3,15,20,7],"postorder":[9,15,7,20,3]}
Output: [3,9,20,null,null,15,7]
The last postorder value 3 is the root; 9 hangs left, and 20 roots the right subtree over 15 and 7.

Example 2

Input: {"inorder":[2,1,3],"postorder":[2,3,1]}
Output: [1,2,3]
1 closes the postorder, so it is the root; 2 and 3 split as its left and right children.

Solve this in your browser →

Also on LeetCode ↗