You are given two integer arrays, preorder and inorder. The preorder array lists the node values of a binary tree in the order they are visited during a preorder traversal (root, then left subtree, then right subtree), while inorder lists them in inorder traversal order (left subtree, then root, then right subtree).
Every value in the tree is unique. Reconstruct the original binary tree and return its root.
Example 1
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
3 is the root because it comes first in preorder. In inorder it sits at index 1, so [9] forms the left subtree and [15,20,7] forms the right subtree, which recursion rebuilds.
Example 2
Input: preorder = [-1], inorder = [-1]
Output: [-1]
A single value yields a tree that contains only the root node.
Constraints
1 <= preorder.length <= 3000inorder.length == preorder.length-3000 <= preorder[i], inorder[i] <= 3000preorder and inorder consist of unique values.Each value of inorder also appears in preorder.preorder is guaranteed to be the preorder traversal of the tree.inorder is guaranteed to be the inorder traversal of the tree.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI