Question

I am trying to print the values of all indices of a given sorted array using postorder traversal. I don't understand what the problem is! Please help me with that. As you know a sorted array is a minheap that here is going to be printed by postorder traversal.

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <cmath>
using namespace std;
int a, b, temp;
char c;
int B[10] = { NULL };

int L(int i) //returning the index of left child
{
    i = ((2 * i) + 1);
    return i;
}

int R(int i) //returning the index of right child
{
    i = ((2 * i) + 2);
    return i;
}

int P(int i) //returning the index of parent
{
    if (i % 2 == 0) { i = ((i - 2) / 2); }
    else { i = ((i - 1) / 2); }
    return i;
}

//printing function
void f(int A[], int i) //printing using post order format 
{
    while (A[L(i)] != NULL && B[L(i)] != 1) 
    {
        i = L(i); 
    }

    cout << A[i] << " A "; 
    B[i] = 1; // B[i] is a kind of flag that checks whether A[i] has already been printed or not 

    if (i == 2) //I noticed that when it approaches the index 2, it only needs to print A[0] and gets out of the function
    {
        cout << A[0] << endl<< endl; 
        return;
    } 

    if (A[L(i+1)] == NULL) 
    {
        cout << A[i + 1] << " "; B[i + 1] = 1; 
    } //checks if the right node hasn't a child, prints it
    else 
    {
        f(A, i + 1); 
    }

        cout << A[P(i)] << " "; B[P(i)] = 1;
// When looking at the parent, if its index is odd, it means that you have already printed a left child so you should go the right index
        if (P(i) % 2 == 1)
        {

            f(A, P(i) + 1);
        }
// When looking at the parent, if its index is even, it means that you have already printed a right child so you should go up to its parent : (P(P(i))
        else 
        {
            f(A, P(P(i))); 
        } 


} 
int main()
{
int A[10]={0,1,2,3,4,5,6,7,8,9};
f(A,0);
return 0;
}
Was it helpful?

Solution

First, I don't think int B[10] = { NULL }; is good method for whatever you wanted. If you just want do the postorder traversal, the easier way to implement is:

void postTraversal(int a[], int n)
{
    if (n <=9  && n >= 0)
    {
        postTraversal(a, L(n));
        postTraversal(a, R(n));
        cout << a[n] << " ";
    }

}
int main()
{
int A[10]={0,1,2,3,4,5,6,7,8,9};
//f(A,0);
postTraversal(A, 0);
cout << endl;
return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top