Course contentsShow
← C
Lesson 1026 of 1,21914. Data Structures in CFree lesson

Pre-order and Post-order traversal

Pre-order and Post-order traversal

What you'll learn: How to navigate a Binary Search Tree by visiting nodes in different sequences to perform specific tasks like copying or deleting a tree.

The "When" of Visiting

In our previous lesson on In-order traversal, we visited nodes from left to right to get sorted data. However, the order in which we "process" a node relative to its children changes what we can do with the tree. Think of a tree like a corporate hierarchy: do you talk to the boss first, or the employees?

Pre-order: The Root First

In Pre-order traversal, you visit the Root, then the Left subtree, then the Right subtree (Root-L-R).

Imagine you are photocopying a family tree. You need to see the parent before you can even know who the children are. Because Pre-order visits the root first, it is the perfect method for creating a complete copy of a tree or serializing it into a file. You record the "header" (the node) before moving into the details (the children).

Post-order: The Children First

In Post-order traversal, you visit the Left subtree, then the Right subtree, and finally the Root (L-R-Root).

Think of this like a demolition crew. If you want to take down a building safely, you clear out the rooms on the bottom floors before collapsing the roof. If you deleted the root node first, you would lose the pointers to its children, leaving them "orphaned" in memory. Therefore, Post-order is the standard way to delete or free a tree from memory.

Seeing the Code

Both methods use recursion. The only difference is where you place the "visit" action (like a printf or a free call).

struct Node {
    int data;
    struct Node *left, *right;
};

// Pre-order: Root, Left, Right
void printPreOrder(struct Node* node) {
    if (node == NULL) return;
    
    printf("%d ", node->data); // Visit root first
    printPreOrder(node->left);
    printPreOrder(node->right);
}

// Post-order: Left, Right, Root
void printPostOrder(struct Node* node) {
    if (node == NULL) return;

    printPostOrder(node->left);
    printPostOrder(node->right);
    printf("%d ", node->data); // Visit root last
}

Key takeaway

Use Pre-order (Root-L-R) to copy or clone a tree, and Post-order (L-R-Root) to safely delete or free a tree.