Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal arrays of a binary tree, construct the original tree and return its root as a level-order array. Pattern focus: Inorder DFS (Left Root Right). The inorder array lets you split left and right subtrees around the root.

Input Format

preorder = preorder traversal, inorder = inorder 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 = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Output:

[3,9,20,null,null,15,7]

Explanation:

This is the standard reconstruction example.

Example 2:

Input:

preorder = [1]
inorder = [1]

Output:

[1]

Explanation:

A single-node tree reconstructs directly.

Loading...
Construct Binary Tree from Preorder and…