AlgoMaster Logo

Construct Binary Tree from Inorder and Postorder Traversal

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Solution

Intuition:

In a binary tree, the postorder traversal visits the left subtree, the right subtree, and the node itself. The last element in the postorder array is the root of the tree. For the inorder array, the left subtree is on its left, and the right subtree is on its right. We can recursively build the tree using these properties.

Explanation:

  1. The last element in the postorder traversal is always the root node.
  2. Find this root in the inorder array. The inorder array splits into left and right subtrees based on the root's position.
  3. Recursively build the left and right subtrees using the same logic.

Code:

2. Optimized Recursive Solution Using HashMap

Intuition:

To improve the efficiency of finding the root index in the inorder traversal, we can use a HashMap to store the indices of elements in the inorder array. This allows us to find the root index in O(1) time.

Explanation:

  1. HashMap is used to store the indices of each value in inorder traversal.
  2. We find the root element position from the map directly, reducing time complexity.

Code: