
Problem
Solution
Submissions
Construct Binary Tree
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to construct a binary tree from its preorder and inorder traversal arrays. You may assume that duplicates do not exist in the tree. The preorder traversal visits nodes in the order: root, left subtree, right subtree. The inorder traversal visits nodes in the order: left subtree, root, right subtree.
Example 1
- Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
- Output: [3,9,20,null,null,15,7]
- Explanation:
- The first element in preorder (3) is the root of the tree.
- Find 3 in inorder array at index 1.
- Elements to the left of 3 in inorder ([9]) form the left subtree.
- Elements to the right of 3 in inorder ([15,20,7]) form the right subtree.
- Recursively construct left and right subtrees using the same logic.
- The first element in preorder (3) is the root of the tree.
Example 2
- Input: preorder = [-1], inorder = [-1]
- Output: [-1]
- Explanation:
- The preorder array has only one element (-1).
- This single element is the root of the tree.
- There are no left or right subtrees.
- The resulting tree has only one node with value -1.
- The preorder array has only one element (-1).
Constraints
- 1 ≤ preorder.length ≤ 3000
- inorder.length == preorder.length
- -3000 ≤ preorder[i], inorder[i] ≤ 3000
- preorder and inorder consist of unique values
- Each value of inorder also appears in preorder
- Time Complexity: O(n)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- The first element in preorder is always the root of the current subtree
- Find the root's position in the inorder array to determine left and right subtrees
- Use a hash map to store inorder indices for O(1) lookup time
- Recursively construct left subtree using elements before root in inorder
- Recursively construct right subtree using elements after root in inorder
- Keep track of preorder index to get the next root for each recursive call