Given an array arr[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Wednesday 24 June 2020

Given an array arr[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal.

Given an array arr[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal.


Given an array arr[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal.
Given an array arr[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal.

Example:
Input:
3
5
40 30 35 80 100
8
40 30 32 35 80 90 100 120

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


#include <bits/stdc++.h>

using namespace std;

void pretopost(int a[], int mn, int mx, int n, int & index) {
    if (index == n || a[index] < mn || a[index] > mx) return;
    int key = a[index];
    index++;
    pretopost(a, mn, key, n, index);
    pretopost(a, key, mx, n, index);
    cout << key << " ";
}

int main() {
    //code
    int t;
    cin >> t;
    while (t--) {
        int n, ind = 0;
        cin >> n;
        int a[n];
        for (int i = 0; i < n; ++i) {
            cin >> a[i];
        }

        pretopost(a, INT_MIN, INT_MAX, n, ind);
        cout << "\n";
    }
    return 0;
}

Second solution of this question:
#include<bits/stdc++.h>
using namespace std;
void prepost(int arr[], int left,int right)
{
    if(left>=right)
    return;
    int start=arr[left];
    int ls=left+1;
    int le=right+1;
   
    for(int i=left+1;i<=right;i++)
    {
        if(arr[i]>start)
        {
            le=i;
            break;
            
            
        }
        
    }
    prepost(arr,ls,le-1);
    prepost(arr,le,right);
    for(int i=left;i<right;i++)
    {
        arr[i]=arr[i+1];
    }
    arr[right]=start;
    
}
int main()
 {
	//code
	int t;
	cin>>t;
	while(t--)
	{
	    int n;
	    cin>>n;
	    int arr[n];
	    for(int i=0;i<n;i++)
	    {
	        cin>>arr[i];
	    }
	    prepost(arr,0,n-1);
	     for(int i=0;i<n;i++)
	    {
	        cout<<arr[i]<<" ";
	    }
	    cout<<endl;
	}
	return 0;
}