AlgoMaster Logo

Construct Binary Tree from Preorder and Inorder Traversal

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Construction (Naive)

Intuition:

The main idea is to understand the properties of preorder and inorder traversal:

  • In preorder traversal, the first element is always the root of the tree.
  • In inorder traversal, the elements left of the root belong to the left subtree and the elements right of the root belong to the right subtree.

We can recursively construct the tree by following these steps:

  1. Identify the root from the preorder list.
  2. Find the index of this root in the inorder list.
  3. Split the inorder list into left and right subtrees.
  4. Recursively build the left and right subtrees.

Code:

2. Optimized Recursive Construction using HashMap

Intuition:

The inefficiency in the previous approach is due to scanning the inorder array to find the root index. We can use a HashMap to store the index of each value in the inorder array, allowing O(1) lookup for the root index.

Code: