VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-tree-from-given-inorder-and-preorder-traversal/

⇱ Binary Tree from Inorder and Preorder traversals - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Binary Tree from Inorder and Preorder traversals

Last Updated : 8 Oct, 2025

Given inorder and preorder traversals of a Binary Tree in array inorder[] and preorder[] respectively, Construct the Binary Tree and return it’s root.

Note: All values in inorder[] and preorder[] are distinct.

Example:

Input: inorder[] = [3, 1, 4, 0, 5, 2], preorder[] = [0, 1, 3, 4, 2, 5]
Output: [[0], [1, 2], [3, 4, 5, N]]
Explanation: The tree will look like:

πŸ‘ construct-tree-from-given-inorder-and-preorder-traversals

[Approach 1] Using Pre-order traversal - O(n2) Time and O(h) Space

The idea is to construct the tree using pre-order traversal. Take the first element of the pre-order array and create root node. Find the index of this node in the in-order array. Create the left subtree using the elements present on left side of root node in in-order array. Similarly create the right subtree using the elements present on the right side of the root node in in-order array.



Output
0 
1 2 
3 4 5 N 

[Approach 2] Using Pre-order traversal and Hash map - O(n) Time and O(n) Space

The idea is similar to first approach, but instead of linearly searching the in-order array for each node we can use hashing. Map the values of in-order array to its indices. This will reduce the searching complexity from O(n) to O(1).


Output
0 
1 2 
3 4 5 N 

Related articles:

Comment