You have been given an array ‘postOrder’ consisting of ‘N’ elements. The array represents the post order traversal of a Binary Search Tree(BST). You need to construct the BST from this post order traversal.
Note: A Binary Search Tree (BST) is a binary tree data structure that has the following properties -
• The left subtree of a node contains only nodes with data less than the node’s data.
• The right subtree of a node contains only nodes with data greater than the node’s data.
• Both the left and right subtrees must also be binary search trees.
For Example:
For the given post order traversal: 2 4 3 7 6 5
The BST will be:
The Inorder Traversal of this BST is 2 3 4 5 6 7.
The first line of the input contains a single integer 'T', representing the number of test cases.
The first line of each test case contains an integer 'N', which denotes the number of nodes in the tree.
The second line of each test case contains ‘N’ single space-separated integers denoting the post-order traversal of the tree.
Output Format:
For each test case, print the inorder traversal of the BST.
Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^5
0 <= postOrder[i] <= 10^5
Time Limit: 1 sec
2
7
8 12 10 16 25 20 15
3
1 3 2
8 10 12 15 16 20 25
1 2 3
Test Case 1: For the given post-order traversal, the BST can be represented as follows
The inorder traversal of this BST is 8 10 12 15 16 20 25.
Test Case 2: For the given post-order traversal, the BST can be represented as follows
The inorder traversal of this BST is 1 2 3.
2
2
10 5
1
20
5 10
20
Think of finding the position for every number by recursively traversing the tree.
The basic idea is to find the position of every node in the tree. The last element of the post order is always the root of the tree. The elements smaller than root should be present in the left subtree, and elements greater than root should be present in the right subtree to satisfy BST conditions. So, we find the last element index, which is smaller than the root, and divide the array to build the BST.
Here is the algorithm :
HELPER(‘postORDER’, ‘LOW’, ‘HIGH’) (where ‘postOrder’ is the given array, ‘LOW’ and ‘HIGH’ are indexes of the array initialized from 0 to ‘N’ - 1).
O(N^2), where ‘N’ is the number of nodes in the tree.
We traverse the array once to find the last index of the array smaller than the root, which can take O(N) time, and then build a tree recursively, which takes O(N) time. Therefore, the overall time complexity will be O(N^2).
O(N), where ‘N’ is the number of nodes in the tree.
The recursive stack can contain at most ‘N’ nodes of the binary tree. Therefore, the overall space complexity will be O(N).