Practice
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Frontend UI Machine Coding
Resources
Career Advice and Roadmaps
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Backend Development
Frontend Development
Project Ideas for Software Developers
Core Computer Science
Companies
SDE Jobs & Internships
Interview Questions
Compare Companies
IDE
Online IDE
Collaborative IDE

Construct Binary Tree from Preorder and Inorder Traversal Editorial

DSA Editorial, Solution and Code

Practice Problem Link: Construct Binary Tree from Preorder and Inorder Traversal

Please make sure to try solving the problem yourself before looking at the editorial.

Problem Statement

Given the preorder and inorder traversals of a binary tree, construct and return the binary tree.

Naive Approach

The problem can be solved recursively based on the fact that in preorder traversal the root is visited first followed by its nodes.

  • Pick an element from the preorder traversal and create a new node using that element say currNode.
  • Search the index of that element in the inorder traversal. Let the index be currInorderIndex.
  • All the elements before the currInorderIndex must be part of the left subtree of the currNode and all the elements after it must be part of the right subtree of the currNode.
  • Recursively repeat the above steps for the elements before the currInorderIndex and make them the left subtree of the currNode.
  • Recursively repeat the above steps for the elements after the currInorderIndex and make them the right subtree of the currNode.
  • Return currNode.

Analysis

  • Time Complexity: O(n2)
  • Auxiliary Space Complexity: O(1)

Implementation

C++
/* This is the Node class definition

class Node {
public:
    Node* left;
    Node* right;
    int data;

    Node(int data) {
        this->left = NULL;
        this->right = NULL;
        this->data = data;
    }
};
*/
Node* constructTreeUtil(vector<int> &preorder, int &preorderIndex, vector<int> &inorder, int inorderStart, int inorderEnd) {
	if (inorderStart > inorderEnd) {
		return NULL;
	}
	Node* currNode = new Node(preorder[preorderIndex]);
	preorderIndex++;
	if (inorderStart == inorderEnd) {
		return currNode;
	}
	int currInorderIndex = - 1;
	for (int i = inorderStart; i <= inorderEnd; i++) {
		if(inorder[i] == currNode->data) {
			currInorderIndex = i;
			break;
		}
	}
	currNode->left = constructTreeUtil(preorder, preorderIndex, inorder, inorderStart, currInorderIndex - 1);
	currNode->right = constructTreeUtil(preorder, preorderIndex, inorder, currInorderIndex + 1, inorderEnd);
	return currNode;
}
Node* constructTree(vector<int> &preorder, vector<int> &inorder) {
	int preorderIndex = 0;
    return constructTreeUtil(preorder, preorderIndex, inorder, 0, inorder.size() - 1);
}
Java
/* This is the Node class definition

class Node {
	public Node left;
    public Node right;
    int data;

    Node(int data) {
        this.data = data;
    }
}
*/

class Solution {
	static int preorderIndex;
	Node constructTreeUtil(int[] preorder, int[] inorder, int inorderStart, int inorderEnd) {
		if (inorderStart > inorderEnd) {
			return null;
		}
		Node currNode = new Node(preorder[preorderIndex]);
		preorderIndex++;
		if (inorderStart == inorderEnd) {
			return currNode;
		}
		int currInorderIndex = - 1;
		for (int i = inorderStart; i <= inorderEnd; i++) {
			if(inorder[i] == currNode.data) {
				currInorderIndex = i;
				break;
			}
		}
		currNode.left = constructTreeUtil(preorder, inorder, inorderStart, currInorderIndex - 1);
		currNode.right = constructTreeUtil(preorder, inorder, currInorderIndex + 1, inorderEnd);
		return currNode;
	}
	Node constructTree(int[] preorder, int[] inorder) {
		preorderIndex = 0;
		return constructTreeUtil(preorder, inorder, 0, inorder.length - 1);
	}
}

Optimal Approach

The naive approach can be optimized by storing the indexes of inorder traversal in a hashmap. By doing this, searching can be done in O(1) time.

Analysis

  • Time Complexity: O(n)
  • Auxiliary Space Complexity: O(n)

Implementation

C++
/* This is the Node class definition

class Node {
public:
    Node* left;
    Node* right;
    int data;

    Node(int data) {
        this->left = NULL;
        this->right = NULL;
        this->data = data;
    }
};
*/
unordered_map<int, int> inorderIndex;
Node* constructTreeUtil(vector<int> &preorder, int &preorderIndex, vector<int> &inorder, int inorderStart, int inorderEnd) {
	if (inorderStart > inorderEnd) {
		return NULL;
	}
	Node* currNode = new Node(preorder[preorderIndex]);
	preorderIndex++;
	if (inorderStart == inorderEnd) {
		return currNode;
	}
	int currInorderIndex = inorderIndex[currNode->data];
	currNode->left = constructTreeUtil(preorder, preorderIndex, inorder, inorderStart, currInorderIndex - 1);
	currNode->right = constructTreeUtil(preorder, preorderIndex, inorder, currInorderIndex + 1, inorderEnd);
	return currNode;
}
Node* constructTree(vector<int> &preorder, vector<int> &inorder) {
	inorderIndex.clear();
	for (int i = 0; i < inorder.size(); i++) {
		inorderIndex[inorder[i]] = i;
	}
	int preorderIndex = 0;
    return constructTreeUtil(preorder, preorderIndex, inorder, 0, inorder.size() - 1);
}
Java
/* This is the Node class definition

class Node {
	public Node left;
    public Node right;
    int data;

    Node(int data) {
        this.data = data;
    }
}
*/

class Solution {
	HashMap<Integer, Integer> inorderIndex = new HashMap<Integer, Integer>();
	static int preorderIndex;
	Node constructTreeUtil(int[] preorder, int[] inorder, int inorderStart, int inorderEnd) {
		if (inorderStart > inorderEnd) {
			return null;
		}
		Node currNode = new Node(preorder[preorderIndex]);
		preorderIndex++;
		if (inorderStart == inorderEnd) {
			return currNode;
		}
		int currInorderIndex = inorderIndex.get(currNode.data);
		currNode.left = constructTreeUtil(preorder, inorder, inorderStart, currInorderIndex - 1);
		currNode.right = constructTreeUtil(preorder, inorder, currInorderIndex + 1, inorderEnd);
		return currNode;
	}
	Node constructTree(int[] preorder, int[] inorder) {
		inorderIndex.clear();
		for (int i = 0; i < inorder.length; i++) {
			inorderIndex.put(inorder[i], i);
		}
		preorderIndex = 0;
		return constructTreeUtil(preorder, inorder, 0, inorder.length - 1);
	}
}
Related Content
Balanced Binary Tree
Binary Search Tree (BST) Iterator
Binary Tree to Doubly Linked List
Binary Tree Inorder Traversal
Maximum Path Sum of Binary Tree
Binary Tree Postorder Traversal
Binary Tree Preorder Traversal
Bottom View of Binary Tree
Construct Binary Tree from Inorder and Postorder Traversal
Delete Node in a Binary Search Tree (BST)
Diameter of Binary Tree
Flatten Binary Tree to Linked List
Identical Binary Trees
Inorder Predecessor of Node in BST
Inorder Successor of Node in BST
Insert into a Binary Search Tree (BST)
Invert Binary Tree
Is Binary Tree BST
Kth Largest in BST
Kth Smallest in BST
Left View of Binary Tree
Level Order of Binary Tree
Lowest Common Ancestor in Binary Tree
Lowest Common Ancestor in BST
Maximum Depth of Binary Tree
Populating Next Right Pointers in Each Node
Right View of Binary Tree
Search in a Binary Search Tree (BST)
Serialize and Deserialize Binary Search Tree (BST)
Size of the Largest BST in a Binary Tree
Symmetric Binary Tree
Top View of Binary Tree
Two Sum in BST
Binary Tree Zigzag Level Order Traversal
SDE Bootcamp - Become a software engineer at a product-based company
Practice Data Structures & Algorithms
Learning Resources
Interview Prep Resources
Community
Join our community
Blog
  • Career Advice and Roadmaps
  • Data Structures & Algorithms
  • Machine Coding Round (LLD)
  • System Design & Architecture
  • Backend Development
  • Frontend Development
  • Awesome Project Ideas
  • Core Computer Science
Practice Questions
  • Machine Coding (LLD) Questions
  • System Design (HLD) Questions
  • Topic-wise DSA Questions
  • Company-wise DSA Questions
  • DSA Sheets (Curated Lists)
  • JavaScript Interview Questions
  • Frontend UI Machine Coding Questions
Online Compilers (IDE)
  • Online Java Compiler
  • Online C++ Compiler
  • Online C Compiler
  • Online Python Compiler
  • Online JavaScript Compiler
Topic-wise Problems
  • Dynamic Programming Interview Questions
  • Linked List Interview Questions
  • Graph Interview Questions
  • Backtracking Interview Questions
  • Arrays Interview Questions
  • Trees Interview Questions
Company-wise Problems
  • Amazon Interview Questions
  • Microsoft Interview Questions
  • Google Interview Questions
  • Flipkart Interview Questions
  • Adobe Interview Questions
  • Facebook Interview Questions
DSA Sheets (Curated Lists)
  • Top Interview Questions
  • FAANG Interview Questions
  • Most Asked Interview Questions
  • 6 month DSA Practice Sheet
  • 3 month DSA Practice Sheet
  • Last minute DSA Practice Sheet