Print Postorder traversal from given Inorder and Preorder traversals
Last Updated :
18 Jan, 2023
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 6
A naive method is to first construct the tree, then use a simple recursive method to print postorder traversal of the constructed tree.
We can print postorder traversal without constructing the tree. The idea is, root is always the first item in preorder traversal and it must be the last item in postorder traversal. We first recursively print left subtree, then recursively print right subtree. Finally, print root.
To find boundaries of left and right subtrees in pre[] and in[], we search root in in[], all elements before root in in[] are elements of left subtree, and all elements after root are elements of right subtree. In pre[], all elements after index of root in in[] are elements of right subtree. And elements before index (including the element at index and excluding the first element) are elements of left subtree.
Implementation:
C++
#include <iostream>
using namespace std;
int search( int arr[], int x, int n)
{
for ( int i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
void printPostOrder( int in[], int pre[], int n)
{
int root = search(in, pre[0], n);
if (root != 0)
printPostOrder(in, pre + 1, root);
if (root != n - 1)
printPostOrder(in + root + 1, pre + root + 1, n - root - 1);
cout << pre[0] << " " ;
}
int main()
{
int in[] = { 4, 2, 5, 1, 3, 6 };
int pre[] = { 1, 2, 4, 5, 3, 6 };
int n = sizeof (in) / sizeof (in[0]);
cout << "Postorder traversal " << endl;
printPostOrder(in, pre, n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG
{
static int search( int arr[], int x, int n)
{
for ( int i = 0 ; i < n; i++)
if (arr[i] == x)
return i;
return - 1 ;
}
static void printPostOrder( int in1[],
int pre[], int n)
{
int root = search(in1, pre[ 0 ], n);
if (root != 0 )
printPostOrder(in1, Arrays.copyOfRange(pre, 1 , n), root);
if (root != n - 1 )
printPostOrder(Arrays.copyOfRange(in1, root+ 1 , n),
Arrays.copyOfRange(pre, 1 +root, n), n - root - 1 );
System.out.print( pre[ 0 ] + " " );
}
public static void main(String args[])
{
int in1[] = { 4 , 2 , 5 , 1 , 3 , 6 };
int pre[] = { 1 , 2 , 4 , 5 , 3 , 6 };
int n = in1.length;
System.out.println( "Postorder traversal " );
printPostOrder(in1, pre, n);
}
}
|
Python3
def search(arr, x, n):
for i in range (n):
if (arr[i] = = x):
return i
return - 1
def printPostOrder(In, pre, n):
root = search(In, pre[ 0 ], n)
if (root ! = 0 ):
printPostOrder(In, pre[ 1 :n], root)
if (root ! = n - 1 ):
printPostOrder(In[root + 1 : n],
pre[root + 1 : n],
n - root - 1 )
print (pre[ 0 ], end = " " )
In = [ 4 , 2 , 5 , 1 , 3 , 6 ]
pre = [ 1 , 2 , 4 , 5 , 3 , 6 ]
n = len (In)
print ( "Postorder traversal " )
printPostOrder(In, pre, n)
|
C#
using System;
class GFG
{
static int search( int []arr,
int x, int n)
{
for ( int i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
static void printPostOrder( int []in1,
int []pre, int n)
{
int root = search(in1, pre[0], n);
int []ar;
if (root != 0)
{
ar = new int [n - 1];
Array.Copy(pre, 1, ar, 0, n - 1);
printPostOrder(in1, ar, root);
}
if (root != n - 1)
{
ar = new int [n - (root + 1)];
Array.Copy(in1, root + 1, ar, 0,
n - (root + 1));
int []ar1 = new int [n - (root + 1)];
Array.Copy(pre, root + 1, ar1, 0,
n - (root + 1));
printPostOrder(ar, ar1, n - root - 1);
}
Console.Write(pre[0] + " " );
}
public static void Main(String []args)
{
int []in1 = { 4, 2, 5, 1, 3, 6 };
int []pre = { 1, 2, 4, 5, 3, 6 };
int n = in1.Length;
Console.WriteLine( "Postorder traversal " );
printPostOrder(in1, pre, n);
}
}
|
Javascript
<script>
function search(arr , x , n)
{
for ( var i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
function printPostOrder( in1,
pre , n)
{
var root = search(in1, pre[0], n);
if (root != 0)
printPostOrder(in1, pre.slice(1, n), root);
if (root != n - 1)
printPostOrder(in1.slice(root+1, n),
pre.slice(1+root, n), n - root - 1);
document.write( pre[0] + " " );
}
var in1 = [ 4, 2, 5, 1, 3, 6 ];
var pre = [ 1, 2, 4, 5, 3, 6 ];
var n = in1.length;
document.write( "Postorder traversal <br>" );
printPostOrder(in1, pre, n);
</script>
|
Output
Postorder traversal
4 5 2 6 3 1
Time Complexity: O(N), where N is the number of nodes in the binary tree. We process every node once, so the time complexity is linear.
Auxiliary Space: O(N). We need to store the recursive calls in the system stack, and in the worst case, the tree is skewed and the height is N. So we need O(N) space for the system stack.
Implementation:
C++
#include <iostream>
using namespace std;
int preIndex = 0;
int search( int arr[], int startIn, int endIn, int data)
{
int i = 0;
for (i = startIn; i < endIn; i++)
{
if (arr[i] == data)
{
return i;
}
}
return i;
}
void printPost( int arr[], int pre[], int inStrt, int inEnd)
{
if (inStrt > inEnd)
{
return ;
}
int inIndex = search(arr, inStrt, inEnd,pre[preIndex++]);
printPost(arr, pre, inStrt, inIndex - 1);
printPost(arr, pre, inIndex + 1, inEnd);
cout << arr[inIndex] << " " ;
}
int main()
{
int arr[] = {4, 2, 5, 1, 3, 6};
int pre[] = {1, 2, 4, 5, 3, 6};
int len = sizeof (arr)/ sizeof (arr[0]);
printPost(arr, pre, 0, len - 1);
}
|
Java
public class PrintPost {
static int preIndex = 0 ;
void printPost( int [] in, int [] pre, int inStrt, int inEnd)
{
if (inStrt > inEnd)
return ;
int inIndex = search(in, inStrt, inEnd, pre[preIndex++]);
printPost(in, pre, inStrt, inIndex - 1 );
printPost(in, pre, inIndex + 1 , inEnd);
System.out.print(in[inIndex] + " " );
}
int search( int [] in, int startIn, int endIn, int data)
{
int i = 0 ;
for (i = startIn; i < endIn; i++)
if (in[i] == data)
return i;
return i;
}
public static void main(String ars[])
{
int in[] = { 4 , 2 , 5 , 1 , 3 , 6 };
int pre[] = { 1 , 2 , 4 , 5 , 3 , 6 };
int len = in.length;
PrintPost tree = new PrintPost();
tree.printPost(in, pre, 0 , len - 1 );
}
}
|
Python3
preIndex = 0
def search(arr, startIn, endIn, data):
i = 0
for i in range (startIn, endIn + 1 ):
if (arr[i] = = data):
return i
return i
def printPost(arr, pre, inStrt, inEnd):
if (inStrt > inEnd):
return
global preIndex
preIndex + = 1
inIndex = search(arr, inStrt, inEnd, pre[preIndex - 1 ])
printPost(arr, pre, inStrt, inIndex - 1 )
printPost(arr, pre, inIndex + 1 , inEnd)
print (arr[inIndex], end = " " )
arr = [ 4 , 2 , 5 , 1 , 3 , 6 ]
pre = [ 1 , 2 , 4 , 5 , 3 , 6 ]
len = len (arr)
printPost(arr, pre, 0 , len - 1 )
|
C#
using System;
class GFG
{
public static int preIndex = 0;
public virtual void printPost( int [] arr, int [] pre,
int inStrt, int inEnd)
{
if (inStrt > inEnd)
{
return ;
}
int inIndex = search(arr, inStrt, inEnd,
pre[preIndex++]);
printPost(arr, pre, inStrt, inIndex - 1);
printPost(arr, pre, inIndex + 1, inEnd);
Console.Write(arr[inIndex] + " " );
}
public virtual int search( int [] arr, int startIn,
int endIn, int data)
{
int i = 0;
for (i = startIn; i < endIn; i++)
{
if (arr[i] == data)
{
return i;
}
}
return i;
}
public static void Main( string [] ars)
{
int [] arr = new int [] {4, 2, 5, 1, 3, 6};
int [] pre = new int [] {1, 2, 4, 5, 3, 6};
int len = arr.Length;
GFG tree = new GFG();
tree.printPost(arr, pre, 0, len - 1);
}
}
|
Javascript
<script>
class GFG {
constructor() {
this .preIndex = 0;
}
printPost(arr, pre, inStrt, inEnd) {
if (inStrt > inEnd) {
return ;
}
var inIndex = this .search(arr, inStrt, inEnd,
pre[ this .preIndex++]);
this .printPost(arr, pre, inStrt, inIndex - 1);
this .printPost(arr, pre, inIndex + 1, inEnd);
document.write(arr[inIndex] + " " );
}
search(arr, startIn, endIn, data) {
var i = 0;
for (i = startIn; i < endIn; i++) {
if (arr[i] == data) {
return i;
}
}
return i;
}
}
var arr = [4, 2, 5, 1, 3, 6];
var pre = [1, 2, 4, 5, 3, 6];
var len = arr.length;
var tree = new GFG();
tree.printPost(arr, pre, 0, len - 1);
</script>
|
Time Complexity: The above function visits every node in the array. For every visit, it calls search which takes O(n) time. Therefore, overall time complexity of the function is O(n2)
Auxiliary Space: O(1)
Implementation: The above solution can be optimized using hashing. We use a HashMap to store elements and their indexes so that we can quickly find the index of an element.
C++
#include<bits/stdc++.h>
using namespace std;
int preIndex = 0;
void printPost( int in[], int pre[], int inStrt,
int inEnd, map< int , int > hm)
{
if (inStrt > inEnd)
return ;
int inIndex = hm[pre[preIndex++]];
printPost(in, pre, inStrt, inIndex - 1, hm);
printPost(in, pre, inIndex + 1, inEnd, hm);
cout << in[inIndex] << " " ;
}
void printPostMain( int in[], int pre[], int n)
{
map< int , int > hm ;
for ( int i = 0; i < n; i++)
hm[in[i]] = i;
printPost(in, pre, 0, n - 1, hm);
}
int main()
{
int in[] = { 4, 2, 5, 1, 3, 6 };
int pre[] = { 1, 2, 4, 5, 3, 6 };
int n = sizeof (pre)/ sizeof (pre[0]);
printPostMain(in, pre, n);
return 0;
}
|
Java
import java.util.*;
public class PrintPost {
static int preIndex = 0 ;
void printPost( int [] in, int [] pre, int inStrt,
int inEnd, HashMap<Integer, Integer> hm)
{
if (inStrt > inEnd)
return ;
int inIndex = hm.get(pre[preIndex++]);
printPost(in, pre, inStrt, inIndex - 1 , hm);
printPost(in, pre, inIndex + 1 , inEnd, hm);
System.out.print(in[inIndex] + " " );
}
void printPostMain( int [] in, int [] pre)
{
int n = pre.length;
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for ( int i= 0 ; i<n; i++)
hm.put(in[i], i);
printPost(in, pre, 0 , n- 1 , hm);
}
public static void main(String ars[])
{
int in[] = { 4 , 2 , 5 , 1 , 3 , 6 };
int pre[] = { 1 , 2 , 4 , 5 , 3 , 6 };
PrintPost tree = new PrintPost();
tree.printPostMain(in, pre);
}
}
|
Python3
def printPost(inn, pre, inStrt, inEnd):
global preIndex, hm
if (inStrt > inEnd):
return
inIndex = hm[pre[preIndex]]
preIndex + = 1
printPost(inn, pre, inStrt, inIndex - 1 )
printPost(inn, pre, inIndex + 1 , inEnd)
print (inn[inIndex], end = " " )
def printPostMain(inn, pre, n):
for i in range (n):
hm[inn[i]] = i
printPost(inn, pre, 0 , n - 1 )
if __name__ = = '__main__' :
hm = {}
preIndex = 0
inn = [ 4 , 2 , 5 , 1 , 3 , 6 ]
pre = [ 1 , 2 , 4 , 5 , 3 , 6 ]
n = len (pre)
printPostMain(inn, pre, n)
|
C#
using System;
class GFG
{
public static int preIndex = 0;
public virtual void printPost( int [] arr, int [] pre,
int inStrt, int inEnd)
{
if (inStrt > inEnd)
{
return ;
}
int inIndex = search(arr, inStrt, inEnd,
pre[preIndex++]);
printPost(arr, pre, inStrt, inIndex - 1);
printPost(arr, pre, inIndex + 1, inEnd);
Console.Write(arr[inIndex] + " " );
}
public virtual int search( int [] arr, int startIn,
int endIn, int data)
{
int i = 0;
for (i = startIn; i < endIn; i++)
{
if (arr[i] == data)
{
return i;
}
}
return i;
}
public static void Main( string [] ars)
{
int [] arr = new int [] {4, 2, 5, 1, 3, 6};
int [] pre = new int [] {1, 2, 4, 5, 3, 6};
int len = arr.Length;
GFG tree = new GFG();
tree.printPost(arr, pre, 0, len - 1);
}
}
|
Javascript
<script>
let preIndex = 0;
function printPost(In, pre, inStrt, inEnd, hm)
{
if (inStrt > inEnd)
return ;
let inIndex = hm.get(pre[preIndex++]);
printPost(In, pre, inStrt, inIndex - 1, hm);
printPost(In, pre, inIndex + 1, inEnd, hm);
document.write(In[inIndex] + " " );
}
function printPostMain(In, pre)
{
let n = pre.length;
let hm = new Map();
for (let i = 0; i < n; i++)
hm.set(In[i], i);
printPost(In, pre, 0, n - 1, hm);
}
let In = [ 4, 2, 5, 1, 3, 6 ];
let pre = [ 1, 2, 4, 5, 3, 6 ];
printPostMain(In, pre);
</script>
|
Time complexity: O(n)
Auxiliary Space : O(n)
Please Login to comment...