Introduction
Construct Tree from Traversals means:
- rebuilding binary tree
using traversal sequences
Common Traversals:
- preorder traversal
- inorder traversal
Preorder Order:
Root → Left → RightInorder Order:
Left → Root → RightGoal:
- reconstruct original tree
using traversal properties
Example:
Preorder:
3 9 20 15 7
Inorder:
9 3 15 20 7
Constructed Tree:
3
/ \
9 20
/ \15 7
Explanation:
Preorder identifies root while inorder splits left and right subtrees. This problem is one of the most important applications of:
DFS TraversalConstraints
1 <= Number of Nodes <= 10^5 Approach : Recursive Tree Reconstruction
Explanations:
Explanation:
The idea is:
- preorder provides root node
- inorder divides subtrees
- recursively rebuild tree
Steps:
- Pick root from preorder.
- Find root index in inorder.
- Split left subtree.
- Split right subtree.
- Recursively build subtrees.
Key Observation:
First preorder element is always root node. This approach:
- uses DFS recursion
- reconstructs exact tree structure
Dry Run
Preorder:3 9 20 15 7
Root:
3
Inorder split:
Left → 9
Right → 15 20 7
Construct left subtree.
Construct right subtree recursively.
Practice :