AlgoTales · Roadmap

Postorder

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Postorder traversal handles all the children of a node first and only then the node itself. It is the natural choice whenever a parent can only be finished once everything beneath it is finished, like deleting a folder or adding up sizes.

Practical use cases

  • Web app: Folder size in a file manager. A cloud-drive page shows "Photos: 2.4 GB". The size of a folder is only known after the sizes of every file and sub-folder inside it are known. Postorder visits the deepest folders first, adds the totals upward, and each folder is calculated exactly once instead of being rescanned.
  • Web app: Deleting a category with all its children. An admin deletes the category "Electronics" in a CMS, and sub-categories and products hang below it. If you delete the parent first you leave orphan rows that no longer belong anywhere. Postorder removes the leaves first, then their parents, so the database never holds a child pointing at a missing parent.
  • System: Build tools and expression evaluation. A build tool must compile a library before the app that depends on it, which is postorder over the dependency tree. A calculator evaluating 3 4 + 2 * also does postorder: both operands are computed before the operator is applied.

The story: Clearing the Wedding Hall

After a huge wedding, Mira's family had to clear the hall. The hall was arranged like a tree: the main stage in the middle, two seating blocks beside it, and each seating block had smaller tables with chairs underneath. Uncle Raju shouted, "Take down the stage first!"

Mrs. Sharma stopped him. "If you remove the stage first, the lights and the speakers attached to it will fall on the ones still standing! Always clear the things that hang from something before clearing that thing itself." So the workers first cleared every chair, then the tables that held them, then the seating blocks, and the main stage was the very last to go.

Kabir tried it out with his toy blocks: remove the left smaller blocks, then the right smaller blocks, then the block they were standing on. Nothing ever fell.

This order, children first, parent last, is called postorder: Left, Right, Root. It is perfect whenever you need the answers of the children before you can finish the parent: deleting, measuring sizes, and adding up totals.

How to spot this problem, and where you need it

You have nested data where a parent's result or removal depends on its children being done first, and doing it in the wrong order leaves orphans or wrong totals.

Signs you need it

  • You need a total, count, height or size for every folder, category or comment thread, and each total is made of the totals below it.
  • Deleting or freeing something fails with "foreign key constraint" or leaves orphan rows because the parent was removed before its children.
  • The words "bottom-up", "children before parent", "evaluate the expression" or "dependencies first" appear in the task.

Where to use it in a project

  • Recursive delete for categories, menus, comment threads and folders stored as parent-child rows.
  • Rolled-up numbers on dashboards: department headcount, folder storage, or total sales per category tree.

The solution

For each node, first call the same function on every child and collect their answers. Only after all children have returned, compute the answer for the node itself: add their sizes plus its own, or delete the node. The order is children first, parent last, so every parent can trust that its children are already complete.

Payoff: Before: orphan rows and a size calculation that rescans folders over and over. After: one clean pass, each node handled once, and deletes that never break links.

Explain it like I am 8

Think of packing up a tent. You first take down all the little things attached to it, and the big tent pole is the last thing you pull out. In postorder, a person only speaks after everyone below them has already spoken.

How it works, step by step

  1. At a node, first handle the whole left subtree.
  2. Then handle the whole right subtree.
  3. Only now visit the node itself.
  4. So the root is always the last thing visited, and each node comes after its children.
  5. Use it when the parent's answer depends on its children's answers (sizes, heights, deleting a tree).

The code in four languages

PHP

<?php
class TreeNode {
    public ?TreeNode $left = null;
    public ?TreeNode $right = null;
    public function __construct(public int $val) {}
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree(): TreeNode {
    $root = new TreeNode(1);
    $root->left = new TreeNode(2);
    $root->right = new TreeNode(3);
    $root->left->left = new TreeNode(4);
    $root->left->right = new TreeNode(5);
    $root->right->right = new TreeNode(6);
    $root->left->right->left = new TreeNode(7);
    return $root;
}

// Postorder: Left, Right, Root
function postorder(?TreeNode $n, array &$out): void {
    if ($n === null) return;          // empty spot: nothing to do
    postorder($n->left, $out);        // 1. whole left side
    postorder($n->right, $out);       // 2. whole right side
    $out[] = $n->val;                 // 3. only now, the node itself
}

// A natural use: count the nodes. A parent needs its children's counts first.
function countNodes(?TreeNode $n): int {
    if ($n === null) return 0;
    return countNodes($n->left) + countNodes($n->right) + 1;
}

$out = [];
postorder(sampleTree(), $out);
echo implode(' ', $out) . PHP_EOL;                       // 4 7 5 2 6 3 1
echo 'Nodes: ' . countNodes(sampleTree()) . PHP_EOL;     // 7

JavaScript

class TreeNode {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree() {
  const root = new TreeNode(1);
  root.left = new TreeNode(2);
  root.right = new TreeNode(3);
  root.left.left = new TreeNode(4);
  root.left.right = new TreeNode(5);
  root.right.right = new TreeNode(6);
  root.left.right.left = new TreeNode(7);
  return root;
}

// Postorder: Left, Right, Root
function postorder(n, out) {
  if (n === null) return;           // empty spot: nothing to do
  postorder(n.left, out);           // 1. whole left side
  postorder(n.right, out);          // 2. whole right side
  out.push(n.val);                  // 3. only now, the node itself
}

// A natural use: count the nodes. A parent needs its children's counts first.
function countNodes(n) {
  if (n === null) return 0;
  return countNodes(n.left) + countNodes(n.right) + 1;
}

const out = [];
postorder(sampleTree(), out);
console.log(out.join(' '));                          // 4 7 5 2 6 3 1
console.log('Nodes: ' + countNodes(sampleTree()));   // 7

Java

import java.util.*;
import java.util.stream.*;

public class Main {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    // The example tree:      1
    //                       /   \
    //                      2     3
    //                     / \     \
    //                    4   5     6
    //                       /
    //                      7
    static TreeNode sampleTree() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(6);
        root.left.right.left = new TreeNode(7);
        return root;
    }

    // Postorder: Left, Right, Root
    static void postorder(TreeNode n, List<Integer> out) {
        if (n == null) return;            // empty spot: nothing to do
        postorder(n.left, out);           // 1. whole left side
        postorder(n.right, out);          // 2. whole right side
        out.add(n.val);                   // 3. only now, the node itself
    }

    // A natural use: count the nodes. A parent needs its children's counts first.
    static int countNodes(TreeNode n) {
        if (n == null) return 0;
        return countNodes(n.left) + countNodes(n.right) + 1;
    }

    public static void main(String[] args) {
        List<Integer> out = new ArrayList<>();
        postorder(sampleTree(), out);
        System.out.println(out.stream().map(String::valueOf).collect(Collectors.joining(" ")));   // 4 7 5 2 6 3 1
        System.out.println("Nodes: " + countNodes(sampleTree()));                                 // 7
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// The example tree:      1
//
//	   /   \
//	  2     3
//	 / \     \
//	4   5     6
//	   /
//	  7
func sampleTree() *TreeNode {
	root := &TreeNode{Val: 1}
	root.Left = &TreeNode{Val: 2}
	root.Right = &TreeNode{Val: 3}
	root.Left.Left = &TreeNode{Val: 4}
	root.Left.Right = &TreeNode{Val: 5}
	root.Right.Right = &TreeNode{Val: 6}
	root.Left.Right.Left = &TreeNode{Val: 7}
	return root
}

// Postorder: Left, Right, Root
func postorder(n *TreeNode, out *[]int) {
	if n == nil {
		return // empty spot: nothing to do
	}
	postorder(n.Left, out)     // 1. whole left side
	postorder(n.Right, out)    // 2. whole right side
	*out = append(*out, n.Val) // 3. only now, the node itself
}

// countNodes is a natural use: a parent needs its children's counts first.
func countNodes(n *TreeNode) int {
	if n == nil {
		return 0
	}
	return countNodes(n.Left) + countNodes(n.Right) + 1
}

// joinInts glues the numbers together with a separator.
func joinInts(xs []int, sep string) string {
	parts := make([]string, len(xs))
	for i, v := range xs {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, sep)
}

func main() {
	out := []int{}
	postorder(sampleTree(), &out)
	fmt.Println(joinInts(out, " "))                 // 4 7 5 2 6 3 1
	fmt.Println("Nodes:", countNodes(sampleTree())) // 7
}

Time: O(n) · Extra space: O(h). One visit per node; the recursion goes as deep as the tree is tall.

Watch out for

  • Deleting a parent before its children, which loses the only way to reach them (a memory leak in languages that need manual cleanup).
  • Confusing postorder with a reversed preorder. Reversing preorder gives Right-Left-Root, not Left-Right-Root.
  • Forgetting that the root is the last value, which is a handy sanity check on your output.

Quick check

  1. What is the postorder of our example tree?
    • 4 2 7 5 1 3 6
    • 4 7 5 2 6 3 1
    • 1 2 4 5 7 3 6
  2. Which task needs postorder thinking?
    • Deleting every node safely
    • Reading a BST in sorted order
    • Copying the tree top-down
  3. Where does the root appear in the postorder output?
    • First
    • In the middle
    • Last