TopicsTreePost-order Traversal
📖

Post-order Traversal

Tree
~20 min read
5 practice problems

Post-order Traversal

Overview

Post-order traversal is a depth-first traversal technique where nodes are visited in the order: Left subtree → Right subtree → Root node. This pattern is particularly useful when you need to process children before their parent, making it ideal for operations like deleting a tree or calculating directory sizes.

Algorithm Steps

  1. Recursively traverse the left subtree

  2. Recursively traverse the right subtree

  3. Visit the root node

Implementation Examples

Recursive Approach (JavaScript)

function postOrderTraversal(root) {
    if (root === null) return [];
    
    const result = [];
    
    // Traverse left subtree
    result.push(...postOrderTraversal(root.left));
    
    // Traverse right subtree
    result.push(...postOrderTraversal(root.right));
    
    // Visit root
    result.push(root.val);
    
    return result;
}

Iterative Approach (using stack)

function postOrderTraversal(root) {
    if (root === null) return [];
    
    const result = [];
    const stack = [root];
    
    while (stack.length > 0) {
        const node = stack.pop();
        result.unshift(node.val); // Add to beginning
        
        // Push left first, then right
        if (node.left) stack.push(node.left);
        if (node.right) stack.push(node.right);
    }
    
    return result;
}

Python Implementation

def post_order_traversal(root):
    if not root:
        return []
    
    result = []
    
    # Traverse left subtree
    result.extend(post_order_traversal(root.left))
    
    # Traverse right subtree
    result.extend(post_order_traversal(root.right))
    
    # Visit root
    result.append(root.val)
    
    return result

Use Cases and Applications

1. Tree Deletion

When deleting a tree, you must delete children before parents:

function deleteTree(node) {
    if (node === null) return;
    
    deleteTree(node.left);   // Delete left subtree
    deleteTree(node.right);   // Delete right subtree
    delete node;            // Delete root
}

2. Expression Tree Evaluation

For evaluating mathematical expressions:

    +
   / \
  *   -
 / \ / \
3  4 5  2

Post-order: Evaluate operands before operator

3. File System Operations

Calculating directory sizes where subdirectories must be processed before parent directories.

Time and Space Complexity

| Aspect | Complexity |

|---------|------------|

| Time | O(n) - Visit each node once |

| Space | O(h) - h = height of tree (recursion stack) |

| Worst Case | O(n) - Skewed tree |

| Best Case | O(log n) - Balanced tree |

Common Variations

Morris Traversal (Space Optimized)

function morrisPostOrder(root) {
    const result = [];
    let current = root;
    
    while (current !== null) {
        if (current.right === null) {
            result.unshift(current.val);
            current = current.left;
        } else {
            // Find inorder successor
            let successor = current.right;
            while (successor.left !== null && successor.left !== current) {
                successor = successor.left;
            }
            
            if (successor.left === null) {
                result.unshift(current.val);
                successor.left = current;
                current = current.right;
            } else {
                successor.left = null;
                current = current.left;
            }
        }
    }
    
    return result;
}

Common Mistakes to Avoid

1. Incorrect Order

// ❌ Wrong - Pre-order instead of post-order
function wrongTraversal(node) {
    if (node === null) return;
    console.log(node.val); // Root first
    traverseLeft(node.left);
    traverseRight(node.right);
}

2. Missing Base Case

// ❌ Wrong - No null check
function incompleteTraversal(node) {
    console.log(node.val);
    postOrderTraversal(node.left);
    postOrderTraversal(node.right);
}

3. Stack Mismanagement

// ❌ Wrong - Pushing in wrong order
function wrongStack(node) {
    const stack = [node];
    while (stack.length > 0) {
        const current = stack.pop();
        result.unshift(current.val);
        // Should push left first, then right
        stack.push(current.right);  // Wrong order
        stack.push(current.left);
    }
}

Comparison with Other Traversals

| Traversal | Order | Use Case |

|------------|---------|------------|

| Pre-order | Root → Left → Right | Tree copying, serialization |

| In-order | Left → Root → Right | BST sorting, expression trees |

| Post-order | Left → Right → Root | Tree deletion, directory size |

Practice Strategy

Beginner Level

  1. Implement basic recursive post-order traversal

  2. Convert between recursive and iterative approaches

  3. Trace through simple tree examples

Intermediate Level

  1. Handle edge cases (empty trees, single nodes)

  2. Implement without recursion using stacks

  3. Modify for specific tree problems

Advanced Level

  1. Morris traversal for O(1) space complexity

  2. Post-order with parent tracking

  3. Complex tree operations using post-order as base

Real-World Applications

1. Compiler Design

Expression tree evaluation in compilers requires post-order processing to handle operands before operators.

2. File System Management

Calculating total directory sizes where subdirectories must be processed before parent directories.

3. Game Development

Scene graph rendering where child objects must be processed before parent objects.

4. Database Systems

Index maintenance and query optimization in hierarchical database structures.

Performance Tips

1. Stack Optimization

Use iterative approach to avoid stack overflow in deep trees.

2. Memory Management

For large trees, consider streaming or batch processing approaches.

3. Early Termination

Implement early termination conditions when specific node values are found.

Common Interview Questions

  1. Print all leaf nodes in post-order

  2. Find kth node in post-order traversal

  3. Check if two trees have same post-order sequence

  4. Convert post-order to tree structure

Related Concepts

Tree Traversal Patterns

  • Pre-order: Root → Left → Right (DFS)

  • In-order: Left → Root → Right (BST property)

  • Post-order: Left → Right → Root (Children before parent)

Tree Operations

  • Binary Tree Properties: Height, depth, diameter

  • Balanced Trees: AVL, Red-Black trees

  • BST Validation: Ensure BST property is maintained

Testing Examples

Test Case 1: Simple Binary Tree

    1
   / \
  2   3
 / \
4   5

Expected Post-order: [4, 5, 2, 3, 1]

Test Case 2: Skewed Tree

    1
     \
      2
       \
        3

Expected Post-order: [3, 2, 1]

Test Case 3: Complete Binary Tree

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

Expected Post-order: [4, 5, 2, 6, 7, 3, 1]

Common Interview Patterns

Pattern 1: Tree Reconstruction

Given post-order and in-order, reconstruct the tree.

Pattern 2: Path Sum Problems

Use post-order to calculate path sums from leaves upward.

Pattern 3: Tree Modification

Modify tree structure while maintaining post-order properties.

Key Takeaways

  1. Post-order is children-first: Always process children before parent

  2. Recursive vs Iterative: Both approaches valid, iterative better for deep trees

  3. Use case driven: Choose based on problem requirements

  4. Edge cases matter: Handle null trees and single nodes properly

This traversal pattern is fundamental for understanding tree algorithms and appears frequently in coding interviews and system design problems.