Construct Binary Tree from Preorder and Inorder

MediumArrayLinked ListTreeBinary Tree

Description

Given two integer arrays preorder and inorder representing the preorder and inorder traversal of a binary tree, construct and return the binary tree.

Examples

Input:preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output:[3,9,20,null,null,15,7]
Explanation:

Reconstruct the tree.

Input:preorder = [-1], inorder = [-1]
Output:[-1]
Explanation:

A single-node tree with value -1. Both traversals contain only this element.

Input:preorder = [1,2,4,5,3,6], inorder = [4,2,5,1,6,3]
Output:[1,2,3,4,5,6]
Explanation:

This demonstrates a more complex tree structure where the root has two subtrees of different heights. The left subtree (rooted at 2) has two children (4,5), while the right subtree (rooted at 3) has only a left child (6).

Constraints

  • 1 ≤ length ≤ 3000

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!