Preorder to Postorder | Practice | GeeksforGeeks

Given an array arr[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal.
In Pre-Order traversal, the root node is visited before the left child and right child nodes.
Post-order traversal is one of the multiple methods to traverse a tree.
Example 1:
Input:
N = 5
arr[]  = {40,30,35,80,100}
Output: 35 30 100 80 40
Explanation: PreOrder: 40 30 35 80 100
InOrder: 30 35 40 80 100
Therefore, the BST will be:
              40
           /      \
         30       80
           \        \   
           35      100
Hence, the postOrder traversal will
be: 35 30 100 80 40
Example 2:
Input:
N = 8
arr[]  = {40,30,32,35,80,90,100,120}
Output: 35 32 30 120 100 90 80 40
Your Task:
You need to complete the given function and return the root of the tree. The driver code will then use this root to print the post order traversal.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= N <= 103
1 <= arr[i] <= 104
0
sajalsa8pt2 days ago
public static Node post_order(int pre[], int size) 
{
    //Your code here
    Node root = new Node(pre[0]);
    for(int i=1;i<pre.length;i++)
        insert(root,pre[i]);
    return root;
} 

public static void insert(Node root, int i)
{
    Node prev = null, curr = root, temp = new Node(i);
    while(curr!=null)
    {
        prev = curr;
        if(curr.data>i)
            curr = curr.left;
        else
            curr = curr.right;
    }
    if(prev.data>i)
        prev.left = temp;
    else
        prev.right = temp;
}
0
2019umt13465 days ago
class Solution{public:   Node* constructTree(int pre[],int &preIndex,int key,int min,int max,int size)    {        if(preIndex>=size)          return NULL;        Node* root=NULL;        if(key>min && key<max)          {              root=newNode(key);              preIndex++;         if(preIndex<size)          {              root->left=constructTree(pre,preIndex,pre[preIndex],min,key,size);          }         if(preIndex<size)          {              root->right=constructTree(pre,preIndex,pre[preIndex],key,max,size);          }          }        return root;    }   //Function that constructs BST from its preorder traversal.   Node* post_order(int pre[], int size)   {       int preorderIndex=0;       return constructTree(pre,preorderIndex,pre[0],INT_MIN,INT_MAX,size);       //code here   }};
+1
mahesh_phutane1 week ago
Java Solution: TC → O(n) SC → O(1)
public static Node solve(int[] pre,int size,int min,int max){
    if(idx>size) return null;
    if(pre[idx]<min || pre[idx]>max) return null;
    Node root = new Node(pre[idx++]);
    root.left = solve(pre,size,min,root.data);
    root.right = solve(pre,size,root.data,max);
    return root;
}
static int idx = 0;
public static Node post_order(int pre[], int size) 
{   
    idx = 0;
    return solve(pre,size-1,Integer.MIN_VALUE,Integer.MAX_VALUE);
} 
+1
prashr11 week ago
Recursive Solution:
 
class Solution{
public:

    Node* po_Util(int pre[],int start,int end)
    {
        Node* root=newNode(pre[start]);
        int x=pre[start],s=start;
        if(start==end)
        {
            root->left=root->right=NULL;
            return root;
        }
        start++;
        while(start<=end && pre[start]<x)
            start++;
            
        if(start>end)
        {
            root->right=NULL;
            root->left=po_Util(pre,s+1,end);
        }
        else if(start==s+1)
        {
            root->left=NULL;
            root->right=po_Util(pre,start,end);
        }
        else
        {
            root->left=po_Util(pre,s+1,start-1);
            root->right=po_Util(pre,start,end);
        }
        return root;
    }
    //Function that constructs BST from its preorder traversal.
    Node* post_order(int pre[], int size)
    {
        //code here
        return po_Util(pre,0,size-1);
    }
};
0
irockstarpiyush1 week ago
C++ -Simple Solution 
Node* f(int pre[], int &ind, int n, int mn, int mx)   {       if(ind >= n){           return NULL;       }       if(!(pre[ind] > mn && pre[ind] < mx)){           return NULL;       }       Node * node = newNode(pre[ind]);       ind++;       node->left = f(pre, ind, n, mn, node->data);       node->right = f(pre, ind, n, node->data, mx);       return node;   }   Node* post_order(int pre[], int size)   {       int ind = 0;       Node* root = f(pre, ind, size, INT_MIN, INT_MAX);       return root;   }
0
yuvrajranabtcse202 weeks ago
c++ 2 ways soln
Node* makeprebystack(int pre[],int size){   stack<Node*> ques;   int i=1;   Node* root= newNode(pre[0]);   Node* p=root;   while(i<size){       if(pre[i]<p->data){           p->left=newNode(pre[i++]);           ques.push(p);           p=p->left;       }       else if(pre[i]>p->data){           if(ques.empty()){               p->right=newNode(pre[i++]);               p=p->right;           }           else if(ques.top()->data>pre[i]){               p->right=newNode(pre[i++]);               p=p->right;           }           else{               p=ques.top();               ques.pop();           }       }   }   return root;   }
/*-------------------------------------------------------------*/Node* makeprebyiteration(int pre[],int size,int &i,int start,int end){   if(i>=size)return NULL;   Node* root=NULL;   int key=pre[i];   if((key>start)&&(key<end)){       Node* root=newNode(key);       i++;       root->left=makeprebyiteration(pre,size,i,start,key);       root->right=makeprebyiteration(pre,size,i,key,end);       return root;   }   return root;}
   Node* post_order(int pre[], int size)   { int i=0;       return makeprebyiteration(pre,size,i,INT_MIN,INT_MAX);}};
0
insanelion2 weeks ago
public static Node post_order(int pre[], int size) 
{
    //Your code here
    
    Node root = new Node(pre[0]);
    Node cur = root;
    Stack<Node> st = new Stack<>();
    st.push(root);
    for(int i=1;i<size;i++) {
        Node node = new Node(pre[i]);
        if(st.peek().data<pre[i]) {
            while(!st.isEmpty()&&st.peek().data<pre[i]) {
                cur = st.pop();
            }
            cur.right = node;
            cur = cur.right;
        }
        else {
            cur.left = node;
            cur = cur.left;
        }
        st.push(node);
    }
    return root;
} 
0
thakursahabsingh122 weeks ago
Java,
public static Node post_order(int pre[], int size) {   //Your code here       return helper(pre, 0, pre.length-1);} public static Node helper(int[] pre, int l, int r){   if(l>r){       return null;   }   Node root= new Node(pre[l]);   int i;   for(i=l;i<=r;i++){       if(pre[i]>root.data){           break;       }   }   root.left = helper(pre, l+1, i-1);   root.right = helper(pre, i, r);   return root;    } 
+1
bagheldikshant1232 weeks ago
java Easy Solution using Recursion
public static Node post_order(int pre[], int size) 
{
    return helper(pre, 0, pre.length-1);
} 
public static Node helper(int[] pre, int l, int r){
    if(l>r){
        return null;
    }
    Node root= new Node(pre[l]);
    int i;
    for(i=l;i<=r;i++){
        if(pre[i]>root.data){
            break;
        }
    }
    root.left = helper(pre, l+1, i-1);
    root.right = helper(pre, i, r);
    return root;
}
+3
avinashdhn19043 weeks ago

class Solution{
public:
    //Function that constructs BST from its preorder traversal.
    Node *build_tree(int pre[],int n,int &i,int mini,int maxi){
        if(i>=n)return NULL;
        if(pre[i]<mini||pre[i]>maxi)return NULL;
        Node *root=(Node *)malloc(sizeof(Node));
     
        root->data=pre[i++];
        
        root->left=build_tree(pre,n,i,mini,root->data);
        root->right=build_tree(pre,n,i,root->data,maxi);
        return root;
    }
  
    Node* post_order(int pre[], int size)
    {
        int i=0,mini=INT_MIN,maxi=INT_MAX;
        Node* root= build_tree(pre,size,i,mini,maxi);
        return root;
    }
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.