Open In App

Find postorder traversal of BST from preorder traversal

Last Updated : 22 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array representing preorder traversal of BST, print its postorder traversal. 

Examples: 

Input : 40 30 35 80 100
Output : 35 30 100 80 40

Input : 40 30 32 35 80 90 100 120
Output : 35 32 30 120 100 90 80 40

Prerequisite: Construct BST from given preorder traversal

Simple Approach: A simple solution is to first construct BST from a given preorder traversal as described in this post. After constructing the tree, perform postorder traversal on it.

Efficient Approach

An efficient approach is to find postorder traversal without constructing the tree. The idea is to traverse the given preorder array and maintain a range in which current element should lie. This is to ensure that the BST property is always satisfied. Initially the range is set to {minval = INT_MIN, maxval = INT_MAX}. In preorder traversal, the first element is always the root, and it will certainly lie in the initial range. 

So store the first element of the preorder array. In postorder traversal, first left and right subtrees are printed and then root data is printed. So first recursive call for left and right subtrees are performed and then the value of root is printed. For left subtree range is updated to {minval, root->data} and for right subtree range is updated to {root->data, maxval}. If the current preorder array element does not lie in the range specified for it, then it does not belong to a current subtree, return from recursive calls until the correct position of that element is not found.

Below is the implementation of the above approach:

C++




// C++ program for finding postorder
// traversal of BST from preorder traversal
#include <bits/stdc++.h>
using namespace std;
 
// Function to find postorder traversal from
// preorder traversal.
void findPostOrderUtil(int pre[], int n, int minval,
                       int maxval, int& preIndex)
{
 
    // If entire preorder array is traversed then
    // return as no more element is left to be
    // added to post order array.
    if (preIndex == n)
        return;
 
    // If array element does not lie in range specified,
    // then it is not part of current subtree.
    if (pre[preIndex] < minval || pre[preIndex] > maxval) {
        return;
    }
 
    // Store current value, to be printed later, after
    // printing left and right subtrees. Increment
    // preIndex to find left and right subtrees,
    // and pass this updated value to recursive calls.
    int val = pre[preIndex];
    preIndex++;
 
    // All elements with value between minval and val
    // lie in left subtree.
    findPostOrderUtil(pre, n, minval, val, preIndex);
 
    // All elements with value between val and maxval
    // lie in right subtree.
    findPostOrderUtil(pre, n, val, maxval, preIndex);
 
    cout << val << " ";
}
 
// Function to find postorder traversal.
void findPostOrder(int pre[], int n)
{
 
    // To store index of element to be
    // traversed next in preorder array.
    // This is passed by reference to
    // utility function.
    int preIndex = 0;
 
    findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex);
}
 
// Driver code
int main()
{
    int pre[] = { 40, 30, 35, 80, 100 };
 
    int n = sizeof(pre) / sizeof(pre[0]);
 
    // Calling function
    findPostOrder(pre, n);
    return 0;
}


Java




// Java program for finding postorder
// traversal of BST from preorder traversal
 
import java.util.*;
 
class Solution {
    static class INT {
        int data;
        INT(int d) { data = d; }
    }
 
    // Function to find postorder traversal from
    // preorder traversal.
    static void findPostOrderUtil(int pre[], int n,
                                  int minval, int maxval,
                                  INT preIndex)
    {
 
        // If entire preorder array is traversed then
        // return as no more element is left to be
        // added to post order array.
        if (preIndex.data == n)
            return;
 
        // If array element does not lie in range specified,
        // then it is not part of current subtree.
        if (pre[preIndex.data] < minval
            || pre[preIndex.data] > maxval) {
            return;
        }
 
        // Store current value, to be printed later, after
        // printing left and right subtrees. Increment
        // preIndex to find left and right subtrees,
        // and pass this updated value to recursive calls.
        int val = pre[preIndex.data];
        preIndex.data++;
 
        // All elements with value between minval and val
        // lie in left subtree.
        findPostOrderUtil(pre, n, minval, val, preIndex);
 
        // All elements with value between val and maxval
        // lie in right subtree.
        findPostOrderUtil(pre, n, val, maxval, preIndex);
 
        System.out.print(val + " ");
    }
 
    // Function to find postorder traversal.
    static void findPostOrder(int pre[], int n)
    {
 
        // To store index of element to be
        // traversed next in preorder array.
        // This is passed by reference to
        // utility function.
        INT preIndex = new INT(0);
 
        findPostOrderUtil(pre, n, Integer.MIN_VALUE,
                          Integer.MAX_VALUE, preIndex);
    }
 
    // Driver code
    public static void main(String args[])
    {
        int pre[] = { 40, 30, 35, 80, 100 };
 
        int n = pre.length;
 
        // Calling function
        findPostOrder(pre, n);
    }
}
 
// This code is contributed
// by Arnab Kundu


Python3




"""Python3 program for finding postorder
traversal of BST from preorder traversal"""
 
INT_MIN = -2**31
INT_MAX = 2**31
 
# Function to find postorder traversal
# from preorder traversal.
 
 
def findPostOrderUtil(pre, n, minval,
                      maxval, preIndex):
 
    # If entire preorder array is traversed
    # then return as no more element is left
    # to be added to post order array.
    if (preIndex[0] == n):
        return
 
    # If array element does not lie in
    # range specified, then it is not
    # part of current subtree.
    if (pre[preIndex[0]] < minval or
            pre[preIndex[0]] > maxval):
        return
 
    # Store current value, to be printed later,
    # after printing left and right subtrees.
    # Increment preIndex to find left and right
    # subtrees, and pass this updated value to
    # recursive calls.
    val = pre[preIndex[0]]
    preIndex[0] += 1
 
    # All elements with value between minval
    # and val lie in left subtree.
    findPostOrderUtil(pre, n, minval,
                      val, preIndex)
 
    # All elements with value between val
    # and maxval lie in right subtree.
    findPostOrderUtil(pre, n, val,
                      maxval, preIndex)
 
    print(val, end=" ")
 
# Function to find postorder traversal.
 
 
def findPostOrder(pre, n):
 
    # To store index of element to be
    # traversed next in preorder array.
    # This is passed by reference to
    # utility function.
    preIndex = [0]
 
    findPostOrderUtil(pre, n, INT_MIN,
                      INT_MAX, preIndex)
 
 
# Driver Code
if __name__ == '__main__':
    pre = [40, 30, 35, 80, 100]
 
    n = len(pre)
 
    # Calling function
    findPostOrder(pre, n)
 
# This code is contributed by
# SHUBHAMSINGH10


C#




// C# program for finding postorder
// traversal of BST from preorder traversal
using System;
 
class GFG {
    public class INT {
        public int data;
        public INT(int d) { data = d; }
    }
 
    // Function to find postorder traversal from
    // preorder traversal.
    public static void findPostOrderUtil(int[] pre, int n,
                                         int minval,
                                         int maxval,
                                         INT preIndex)
    {
 
        // If entire preorder array is traversed
        // then return as no more element is left
        // to be added to post order array.
        if (preIndex.data == n) {
            return;
        }
 
        // If array element does not lie in
        // range specified, then it is not
        // part of current subtree.
        if (pre[preIndex.data] < minval
            || pre[preIndex.data] > maxval) {
            return;
        }
 
        // Store current value, to be printed
        // later, after printing left and right
        // subtrees. Increment preIndex to find
        // left and right subtrees, and pass this
        // updated value to recursive calls.
        int val = pre[preIndex.data];
        preIndex.data++;
 
        // All elements with value between
        // minval and val lie in left subtree.
        findPostOrderUtil(pre, n, minval, val, preIndex);
 
        // All elements with value between
        // val and maxval lie in right subtree.
        findPostOrderUtil(pre, n, val, maxval, preIndex);
 
        Console.Write(val + " ");
    }
 
    // Function to find postorder traversal.
    public static void findPostOrder(int[] pre, int n)
    {
 
        // To store index of element to be
        // traversed next in preorder array.
        // This is passed by reference to
        // utility function.
        INT preIndex = new INT(0);
 
        findPostOrderUtil(pre, n, int.MinValue,
                          int.MaxValue, preIndex);
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int[] pre = new int[] { 40, 30, 35, 80, 100 };
 
        int n = pre.Length;
 
        // Calling function
        findPostOrder(pre, n);
    }
}
 
// This code is contributed by Shrikant13


Javascript




<script>
// Javascript program for finding postorder
// traversal of BST from preorder traversal
     
class INT
{
    constructor(d)
    {
        this.data=d;
    }
}
 
// Function to find postorder traversal from
    // preorder traversal.
function findPostOrderUtil(pre,n,minval,maxval,preIndex)
{
    // If entire preorder array is traversed then
        // return as no more element is left to be
        // added to post order array.
        if (preIndex.data == n)
            return;
  
        // If array element does not lie in range specified,
        // then it is not part of current subtree.
        if (pre[preIndex.data] < minval
            || pre[preIndex.data] > maxval) {
            return;
        }
  
        // Store current value, to be printed later, after
        // printing left and right subtrees. Increment
        // preIndex to find left and right subtrees,
        // and pass this updated value to recursive calls.
        let val = pre[preIndex.data];
        preIndex.data++;
  
        // All elements with value between minval and val
        // lie in left subtree.
        findPostOrderUtil(pre, n, minval, val, preIndex);
  
        // All elements with value between val and maxval
        // lie in right subtree.
        findPostOrderUtil(pre, n, val, maxval, preIndex);
  
        document.write(val + " ");
}
 
 // Function to find postorder traversal.
function findPostOrder(pre,n)
{
    // To store index of element to be
        // traversed next in preorder array.
        // This is passed by reference to
        // utility function.
        let preIndex = new INT(0);
  
        findPostOrderUtil(pre, n, Number.MIN_VALUE,
                          Number.MAX_VALUE, preIndex);
}
 
// Driver code
let pre=[40, 30, 35, 80, 100];
let n = pre.length;
// Calling function
findPostOrder(pre, n);
     
     
// This code is contributed by unknown2108
</script>


Output

35 30 100 80 40

Complexity Analysis:

  • Time Complexity: O(N), where N is the number of nodes. 
  • Auxiliary Space: O(N) (Function call stack size).


Similar Reads

Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order tr
13 min read
Print Postorder traversal from given Inorder and Preorder traversals
AuxiliaryGiven Inorder and Preorder traversals of a binary tree, print Postorder traversal. Example: Input: Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Preorder traversal pre[] = {1, 2, 4, 5, 3, 6} Output: Postorder traversal is {4, 5, 2, 6, 3, 1} Traversals in the above example represents following tree 1 / \ 2 3 / \ \ 4 5 6Recommended PracticePos
15+ min read
Find Leftmost and Rightmost node of BST from its given preorder traversal
Given a preorder sequence of the binary search tree of N nodes. The task is to find its leftmost and rightmost nodes. Examples: Input : N = 5, preorder[]={ 3, 2, 1, 5, 4 } Output : Leftmost = 1, Rightmost = 5 The BST constructed from this preorder sequence would be: 3 / \ 2 5 / / 1 4 Leftmost Node of this tree is equal to 1 Rightmost Node of this t
5 min read
Construct a BST from given postorder traversal using Stack
Given postorder traversal of a binary search tree, construct the BST.For example, If the given traversal is {1, 7, 5, 50, 40, 10}, then following tree should be constructed and root of the tree should be returned. 10 / \ 5 40 / \ \ 1 7 50 Input : 1 7 5 50 40 10 Output : Inorder traversal of the constructed tree: 1 5 7 10 40 50 If the given traversa
9 min read
Construct BST from given preorder traversal using Stack
Given preorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 10 / \ 5 40 / \ \ 1 7 50 We have discussed O(n^2) and O(n) recursive solutions in the previous post. Following is a stack based iterative solution that works in O(n) time
13 min read
Number of elements smaller than root using preorder traversal of a BST
Given a preorder traversal of a BST. The task is to find the number of elements less than root. Examples: Input: preorder[] = {3, 2, 1, 0, 5, 4, 6} Output: 3 Input: preorder[] = {5, 4, 3, 2, 1} Output: 4 For a binary search tree, a preorder traversal is of the form: root, { elements in left subtree of root }, { elements in right subtree of root } S
9 min read
Construct BST from given preorder traversal using Sorting
Given preorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 10 / \ 5 40 / \ \ 1 7 50 We have discussed methods to construct binary search tree in previous posts.Here is another method to construct binary search tree when given pre
10 min read
Construct BST from given preorder traversal | Set 1
Given the preorder traversal of a binary search tree, construct the BST. Examples: Input: {10, 5, 1, 7, 40, 50}Output: 10 / \ 5 40 / \ \ 1 7 50 Recommended: Please try your approach on {IDE} first, before moving on to the solution.Naive approach: To solve the problem follow the below idea: The first element of preorder traversal is always the root.
15+ min read
Construct Full Binary Tree from given preorder and postorder traversals
Given two arrays that represent preorder and postorder traversals of a full binary tree, construct the binary tree. Full Binary Tree is a binary tree where every node has either 0 or 2 children. Illustration: Following are examples of Full Trees. 1 / \ 2 3 / \ / \ 4 5 6 7 1 / \ 2 3 / \ 4 5 / \ 6 7 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 It is not possibl
14 min read
three90RightbarBannerImg