Post-order/Pre-order Traversal of Binary Tree

Man Person picture Man Person · Nov 28, 2012 · Viewed 14k times · Source

I have a pre-order traversal function that looks like this:

void listInPreOrder(node* hd){
if(hd != NULL) {
        printf("%d, ", hd->value);
        listInPreOrder(hd->left);
        listInPreOrder(hd->right);
    }
}

That in fact works, but I thought that making it post order would be as simple as this

void listInPostOrder(node* hd){
if(hd != NULL) {
        listInPreOrder(hd->left);
        listInPreOrder(hd->right);
        printf("%d, ", hd->value);
    }
}

But unfortunately it does not work so well. I'm wondering how to fix this, maybe I'm doing something simple wrong. Or maybe it's completely wrong.

Answer

WhozCraig picture WhozCraig · Nov 28, 2012

How about you change this:

void listInPostOrder(node* hd){
if(hd != NULL) {
        listInPreOrder(hd->left);  // PRE order ???
        listInPreOrder(hd->right); // PRE order ???
        printf("%d, ", hd->value);
    }
}

to this:

void listInPostOrder(node* hd){
if(hd != NULL) {
        listInPostOrder(hd->left);
        listInPostOrder(hd->right);
        printf("%d, ", hd->value);
    }
}