Back to Practice Dashboard
DSA SectionMedium
Tree Construction
Learn how to solve the 'Tree Construction' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Medium
Write a function build_tree(preorder, inorder) that reconstructs a binary tree from its preorder and inorder traversal lists and returns the level-order traversal of the reconstructed tree (represented as a list, with None for empty nodes).
Constraints
- •1 <= len(preorder) <= 1000
- •inorder.length == preorder.length
Examples
Example 1
Input
preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]
Output
[3, 9, 20, None, None, 15, 7]
Explanation
Preorder allows identifying the root 3. Inorder splits left subtree [9] and right subtree [15, 20, 7]. Reconstructed tree has level order [3, 9, 20, None, None, 15, 7].
Need a Hint?
Perform a recursive tree traversal (DFS) or level-order traversal (BFS) using a queue/stack.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.