Construct Binary Tree from Preorder and Inorder Traversal
TreeDFSRecursion
Problem Statement
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
Example
Example 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Constraints
- 1 ≤ preorder.length ≤ 3000
- inorder.length == preorder.length
- -3000 ≤ preorder[i], inorder[i] ≤ 3000
- preorderand- inorderconsist of unique values.
- Each value of inorderalso appears inpreorder.
- preorderis guaranteed to be the preorder traversal of the tree.
- inorderis guaranteed to be the inorder traversal of the tree.
Solution (DFS)
The solution uses a recursive Depth-First Search (DFS) approach to construct the tree. The key idea is to use the preorder traversal to find the root of a subtree and the inorder traversal to find the elements in the left and right subtrees.
Algorithm Steps
- The first element of the preorder traversal is the root of the tree.
- Find the root in the inorder traversal. The elements to the left of the root in the inorder traversal are in the left subtree, and the elements to the right are in the right subtree.
- Recursively call the function to build the left and right subtrees.
- To optimize finding the root in the inorder traversal, we can use a hash map to store the indices of the elements.
Construct Binary Tree from Preorder and Inorder Traversal Solution