You are given a preorder traversal of a binary search tree. Your task is to find the postorder from the preorder.
Return the root of the BST constructed from the given preorder. The driver code will then use this root to print the post-order traversal.
You are given preOrder = [10, 5, 1, 7, 40, 50], the binary search tree from the given preorder traversal is

Hence the answer is [1, 7, 5, 50, 40, 10].
The first line contains a single integer ‘N’ representing the size of the preorder array.
The second line contains ‘N’ space-separated integers representing the preorder traversal of the tree.
Output Format:
The only line contains the postorder of the BST constructed from the given preorder.
Note:
You do not need to print anything. It has already been taken care of. Just implement the function.
6
8 5 1 7 10 12
1 7 5 12 10 8
preOrder = [8, 5, 1, 7, 10, 12], the binary search tree from the given preorder traversal is

Hence the answer is [1, 5, 7, 10, 40, 50].
3
1 3 2
2 3 1
1 <= N <= 10^5
1 <= preorder[i] <= 10^6
Time Limit: 1 sec.
Try using recursion
In this approach, it can be observed that the first element of the preorder array will always be the root of the BST. We can then note that all the elements after the first element, which are less than the root, will be in the left subtree of the root, and all the elements that are larger than the root will be in the right subtree of the root.
Therefore for each root, we create two arrays leftPreOrder, rightPreOrder, then divide the elements of the preOrder traversal into two arrays according to whether the elements are greater than the root element or not.
We will create recursive function util(preOrder), here preOrder is the preOrder traversal of the tree.
Algorithm:
O(N^2), Where ‘N’ is the number of nodes in the tree.
We are iterating over each element in the preorder array, and for each element, we are dividing the array into two subarrays, which will cost O(N^2) time. Hence the final time complexity is O(N^2).
O(N^2), Where ‘N’ is the number of nodes in the tree.
The recursion stack will take O(N) space. For each recursive call, we make two arrays that. will take O(N) space each. Hence the overall space complexity is O(N^2).