VOOZH about

URL: https://www.geeksforgeeks.org/dsa/full-and-complete-binary-tree-from-given-preorder-and-postorder-traversals/

⇱ Binary Tree From Preorder and Postorder traversal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Binary Tree From Preorder and Postorder traversal

Last Updated : 8 Oct, 2025

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

Note: All values in post[] and pre[] are distinct.

Examples:

Input: pre[] = [1, 2, 4, 8, 9, 5, 3, 6, 7], post[] = [8, 9, 4, 5, 2, 6, 7, 3, 1]
Output: [[1], [2, 3], [4, 5, 6, 7], [8, 9, N, N, N, N, N, N]]
Explanation: The tree looks like:

πŸ‘ 420046665


Input: pre[] = [1, 2, 4, 5, 3, 6, 7], post[] = [4, 5, 2, 6, 7, 3, 1]
Output: [[1], [2, 3], [4, 5, 6, 7]]
Explanation: The tree looks like:

πŸ‘ 11

[Approach] Recursive Binary Tree Reconstruction - O(n2) Time and O(n) Space

The main idea is that a general binary tree cannot always be uniquely constructed from preorder and postorder traversals alone, because multiple trees may produce the same pair of traversals. Still, we can reconstruct one valid tree by using the relationship between the traversal orders.

  • The first element in preorder is always the root of the current subtree.
  • The next element in preorder represents the left child, whose position in postorder helps determine the extent of the left subtree.
  • All nodes in postorder up to that position form the left subtree, and the remaining nodes (excluding the root) form the right subtree.
  • We then recursively construct the left and right subtrees using their respective preorder and postorder segments and attach them to the root.

Output
1 
2 3 
4 5 6 7 
8 9 N N N N N N 

[Expected Approach] Using HashMap and Recursion - O(n) Time and O(n) Space

The idea is to use the properties of preorder (NLR) and postorder (LRN) traversals. In preorder, the first element is always the root, which serves as the starting point for constructing the tree. The next element in preorder belongs to the left subtree, and its position in the postorder array helps to divide the tree into two parts: the elements before this position form the left subtree, and the elements after it form the right subtree. To find this position efficiently, we use a HashMap for constant-time lookup, and then recursively split the array to build the left and right subtrees and rebuild the entire tree.


Output
1 
2 3 
4 5 6 7 
8 9 N N N N N N 
Comment
Article Tags:
Article Tags: