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.
We'll cover the following
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 build_binary_tree
function in the skeleton code given below.
Note: 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.