Tutorialspoint
Problem
Solution
Submissions

Binary Tree from Preorder and Inorder

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to construct a binary tree from its preorder and inorder traversal arrays. Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. You may assume that duplicates do not exist in the tree.

Example 1
  • Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
  • Output: Tree structure
  • Explanation: First element in preorder (3) is the root. Find 3 in inorder array at index 1. Elements to the left of 3 in inorder ([9]) form the left subtree. Elements to the right of 3 in inorder ([15,20,7]) form the right subtree. Recursively construct left and right subtrees.
Example 2
  • Input: preorder = [-1], inorder = [-1]
  • Output: Tree structure
  • Explanation: Only one element in both arrays. The root is -1 with no children. Tree construction is complete.
Constraints
  • 1 ≤ preorder.length ≤ 3000
  • inorder.length == preorder.length
  • -3000 ≤ preorder[i], inorder[i] ≤ 3000
  • preorder and inorder consist of unique values
  • Time Complexity: O(n)
  • Space Complexity: O(n)
Functions / MethodsBinary TreeKPMGD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • The first element in preorder is always the root of the tree
  • Find the root element in the inorder array to determine left and right subtrees
  • Elements to the left of root in inorder belong to the left subtree
  • Elements to the right of root in inorder belong to the right subtree
  • Use recursion to construct left and right subtrees
  • Use a hashmap to quickly find indices in inorder array for optimization

Steps to solve by this approach:

 Step 1: Take the first element from preorder array as the root node.
 Step 2: Find the position of this root element in the inorder array.
 Step 3: Split the inorder array into left and right parts based on root position.
 Step 4: The left part of inorder represents the left subtree.
 Step 5: The right part of inorder represents the right subtree.
 Step 6: Recursively build the left subtree using remaining preorder elements and left inorder part.
 Step 7: Recursively build the right subtree using remaining preorder elements and right inorder part.

Submitted Code :