VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-postorder-from-given-inorder-and-preorder-traversals/

⇱ Postorder from given Inorder and Preorder - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Postorder from given Inorder and Preorder

Last Updated : 31 May, 2026

Given two arrays represent Inorder and Preorder traversals of a binary tree, the task is to find the Postorder traversal.

Example:

Input: in[] = [4, 2, 5, 1, 3, 6] pre[] = [1, 2, 4, 5, 3, 6]
Output: 4 5 2 6 3 1
Explanation: Traversals in the above example represents following tree:

šŸ‘ print-postorder-traversal-from-given-inorder-and-preorder-traversals

[Naive Recursive] Searching Root in Inorder - O(n²) Time and O(n) Space

The idea is based on the properties of preorder and inorder traversals. In preorder traversal, the first element is always the root of the current subtree. By searching this root in the inorder traversal, the left and right subtrees can be identified.

  • Take the first element of the current preorder range as the root
  • Find the root's index in the inorder traversal using linear search
  • Recursively process the left and right subtrees
  • Append the root to the postorder traversal

Output
4 5 2 6 3 1 

[Efficient Approach] Hash Map for Inorder Lookup - O(n) Time and O(n) Space

The idea is to avoid repeatedly searching for the root in the inorder traversal. A hash map is used to store the index of every node in the inorder traversal.

  • Store each inorder value and its index in a hash map
  • Maintain a preorder index pointing to the current root
  • For each recursive call: Take the current preorder element as the root and find its inorder position using the hash map
  • Recursively process the left and right subtrees
  • Add the root to the postorder traversal
  • Return the generated postorder traversal

Output
4 5 2 6 3 1 
Comment
Article Tags: