![]() |
VOOZH | about |
Given Inorder Traversal of a Special Binary Tree in which the key of every node is greater than keys in left and right children, construct the Binary Tree and return root.
Examples:
Input: inorder[] = {5, 10, 40, 30, 28}
Output: root of following tree
40
/ \
10 30
/ \
5 28
Input: inorder[] = {1, 5, 10, 40, 30,
15, 28, 20}
Output: root of following tree
40
/ \
10 30
/ \
5 28
/ / \
1 15 20
The idea used in Construction of Tree from given Inorder and Preorder traversals can be used here. Let the given array is {1, 5, 10, 40, 30, 15, 28, 20}. The maximum element in the given array must be root. The elements on the left side of the maximum element are in the left subtree and the elements on the right side are in the right subtree.
40
/ \
{1,5,10} {30,15,28,20}
We recursively follow the above step for left and right subtrees, and finally, get the following tree.
40 / \ 10 30 / \ 5 28 / / \ 1 15 20
Algorithm: buildTree()
- Find index of the maximum element in array. The maximum element must be root of Binary Tree.
- Create a new tree node 'root' with the data as the maximum value found in step 1.
- Call buildTree for elements before the maximum element and make the built tree as left subtree of 'root'.
- Call buildTree for elements after the maximum element and make the built tree as right subtree of 'root'.
- return 'root'.
Below is the implementation of the above approach:
Inorder traversal of the constructed tree is 5 10 40 30 28
Time Complexity: O(n^2)
Auxiliary Space: O(n), The extra space used is due to the recursion call stack.