Construct Binary Tree from Preorder and Postorder Traversal

Given preorder and postorder traversal arrays of a binary tree with distinct values, construct the original tree and return its level-order array. Pattern focus: Construct Tree from Traversals. Use the preorder root and locate the left subtree boundary from the postorder array.

Input Format

preorder = preorder traversal, postorder = postorder traversal

Output Format

level-order array representation of the reconstructed tree

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^4 <= node values <= 10^4
  • Input must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

preorder = [1,2,4,5,3,6,7]
postorder = [4,5,2,6,7,3,1]

Output:

[1,2,3,4,5,6,7]

Explanation:

The traversals correspond to a perfect binary tree.

Example 2:

Input:

preorder = [1]
postorder = [1]

Output:

[1]

Explanation:

A single-node tree is reconstructed directly.

Loading...
Construct Binary Tree from Preorder and…