Lesson 4 of 14

Postorder Traversal

Postorder Traversal

Postorder: left subtree → right subtree → current node

        4
       / \
      2   6
     / \ / \
    1  3 5  7

Postorder visits: 1 3 2 5 7 6 4

The root comes last. Postorder is used when you need to process children before their parent — for example, freeing a tree (you free children before the parent), evaluating expression trees (compute operands before the operator), or deleting a directory (delete files before the folder).

Implementation

void postorder(struct Node *root) {
    if (root == NULL) return;
    postorder(root->left);
    postorder(root->right);
    printf("%d\n", root->val);  // visit root last
}

Summary of the Three Traversals

TraversalOrderUse
Inorderleft → root → rightsorted output from BST
Preorderroot → left → rightcopy a tree
Postorderleft → right → rootfree/delete a tree

Your Task

Implement void postorder(struct Node *root) that prints each node's value, visiting left then right subtrees before the current node.

TCC compiler loading...
Loading...
Click "Run" to execute your code.