DIY: Construct a Binary Tree from Preorder and Inorder Traversal

Solve the interview question "Construct a Binary Tree from Preorder and Inorder Traversal" in this lesson.

Problem statement

Given a preorder and an inorder traversal of a binary tree, your task is to construct and return the binary tree.

Input

The input will be two lists containing the preorder and inorder traversals of the tree:

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Output

Your program should return the entire tree. For the output, we will be show the levelorder traversal of the tree:

[3,9,20,15,7]

Coding exercise

You need to implement the buildBinaryTree() function in the skeleton code given below.

Note: After running the code, click on Show Console to view the trees for the test cases.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.