
Problem
Solution
Submissions
Binary Tree from Preorder and Inorder
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to construct a binary tree from its preorder and inorder traversal arrays. 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. You may assume that duplicates do not exist in the tree.
Example 1
- Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
- Output: Tree structure
- Explanation: First element in preorder (3) is the root. 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.
Example 2
- Input: preorder = [-1], inorder = [-1]
- Output: Tree structure
- Explanation: Only one element in both arrays. The root is -1 with no children. Tree construction is complete.
Constraints
- 1 ≤ preorder.length ≤ 3000
- inorder.length == preorder.length
- -3000 ≤ preorder[i], inorder[i] ≤ 3000
- preorder and inorder consist of unique values
- 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 tree
- Find the root element in the inorder array to determine left and right subtrees
- Elements to the left of root in inorder belong to the left subtree
- Elements to the right of root in inorder belong to the right subtree
- Use recursion to construct left and right subtrees
- Use a hashmap to quickly find indices in inorder array for optimization