![]() |
VOOZH | about |
Given in-order and level-order traversals of a Binary Tree, the task is to construct the Binary Tree and return its root.
Example:
Input:
👁 Construct-a-tree-from-Inorder-and-Level-order-traversals
in[] = {4, 8, 10, 12, 14, 20, 22};
level[] = {20, 8, 22, 4, 12, 10, 14};
Output:
Table of Content
The idea is to map the values of the in-order array to their respective indices in a hash map and construct the root node from the first element of the level order array. Find the index of this element in the in-order array using the hash map. Recursively create the left subtree from the elements present on the left side to the current element in the in-order array. Similarly, create the right subtree from the elements present on the right side to the current element in the in-order array.
Below is the implementation of the above approach:
4 8 10 12 14 20 22
The idea is to construct the root node from the first element of the level order array. Find the index of this element in the in-order array. Then, find the elements in level order array which will be present in left subtree and right subtree using a hashset (Insert the left subtree elements from in-order array in set, then traverse the level-order array and check if the element will be present in left subtree or right subtree). Recursively create the left subtree and right subtree from the elements present on the left and right side to the current element in the in-order array.
Below is the implementation of the above approach:
4 8 10 12 14 20 22
The idea is to use the first element in level order array to create the root node. Find the index of the same element in the in-order array. If elements are present on the left side, then create root->left node. Similarly, if elements are present on the right side, then create root->right node.
Step by step implementation:
Below is the implementation of the above approach:
4 8 10 12 14 20 22
Related articles: