Skip to content
Home DSA Tree Traversals Explained — Inorder, Preorder & Postorder With Real Uses

Tree Traversals Explained — Inorder, Preorder & Postorder With Real Uses

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Trees → Topic 3 of 15
Tree traversals (inorder, preorder, postorder) demystified — learn WHY each order exists, when to use each one, and how they power real software like compilers and file systems.
⚙️ Intermediate — basic DSA knowledge assumed
In this tutorial, you'll learn
Tree traversals (inorder, preorder, postorder) demystified — learn WHY each order exists, when to use each one, and how they power real software like compilers and file systems.
  • Traversals are different 'views' of the same hierarchical data, defined by when the root is visited relative to its children.
  • Inorder = Sorted Order in a BST. If you need to validate if a tree is a BST, an inorder traversal is your best friend.
  • Postorder = Bottom-Up Processing. Use this whenever a parent's value depends on the results of its children (like calculating mathematical expressions or directory sizes).
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer

Imagine your family tree printed on paper. You can read it starting from the oldest ancestor down (preorder), or start from yourself and work up to your grandparents (postorder), or read every person strictly left-to-right across one generation at a time (inorder). Each reading order answers a different question about the same tree — that's exactly what tree traversals do with data. The tree doesn't change; only the order you visit each node does.

Every time your IDE folds or unfolds a directory, every time a compiler evaluates an expression like 3 + (4 * 2), and every time a database engine builds a query plan — a tree traversal is running under the hood. These aren't academic exercises; they're the backbone of tools you use every day. Understanding traversals is what separates developers who can reason about recursive structures from those who just copy-paste solutions and hope for the best.

The problem traversals solve is deceptively simple: a tree has no 'natural' reading order the way an array does. Arrays are linear — element 0, then 1, then 2. Trees branch. You need a deliberate strategy for visiting every node exactly once without missing any or doubling back. The three classical strategies — preorder, inorder, and postorder — each prioritise a different relationship between a node and its children, and that priority determines what the output is useful for.

By the end of this article you'll know not just how to implement all three traversals recursively and iteratively in Java, but — more importantly — you'll know which one to reach for when solving a real problem. You'll be able to look at a coding challenge and immediately say 'this needs postorder because I have to process children before parents' rather than guessing. That intuition is what interviewers are actually testing.

Tree Traversal Algorithms — Plain English and Rules

A binary tree traversal visits every node exactly once. There are four main orders:

Inorder (Left, Root, Right): Visit the left subtree, then the current node, then the right subtree. For a Binary Search Tree, inorder traversal produces elements in sorted ascending order — this is its most important property.

Preorder (Root, Left, Right): Visit the current node first, then recurse into left, then right. Used to create a copy of the tree or serialize it to a flat list.

Postorder (Left, Right, Root): Visit both subtrees before the current node. Used to delete a tree (process children before parent) or evaluate expression trees.

Level-order (BFS): Visit nodes level by level from top to bottom, left to right. Uses a queue, not recursion. Used to find tree height, check if balanced, or serialize by level.

Memory trick: the prefix tells you when the Root is visited relative to children: Pre-order = Root first. In-order = Root in between (2nd). Post-order = Root last.

Worked Example — All Four Traversals on the Same Tree

Tree: 1 / \ 2 3 / \ 4 5

Inorder (L-Root-R): Go left from 1 -> 2 -> 4. 4 has no children. Visit 4. Back to 2. Visit 2. Go right: visit 5. Back to 1. Visit 1. Go right: visit 3. Result: [4, 2, 5, 1, 3]

Preorder (Root-L-R): Visit 1. Go left: visit 2. Go left: visit 4. Back to 2. Go right: visit 5. Back to 1. Go right: visit 3. Result: [1, 2, 4, 5, 3]

Postorder (L-R-Root): Go left from 1 to 2 to 4. Visit 4. Back to 2. Go right to 5. Visit 5. Visit 2. Back to 1. Go right: visit 3. Visit 1. Result: [4, 5, 2, 3, 1]

Level-order (BFS): Level 0: visit 1. Level 1: visit 2, 3. Level 2: visit 4, 5. Result: [1, 2, 3, 4, 5]

The Anatomy of a Traversal: Depth-First Search (DFS) Strategies

In a Depth-First Search, we explore as far as possible along each branch before backtracking. The difference between the three types is simply when you 'visit' (process) the current node relative to its subtrees.

  • Preorder (Root, Left, Right): Visit the parent before the children. Perfect for cloning trees or prefix notation.
  • Inorder (Left, Root, Right): Visit the left child, then the parent, then the right. On a Binary Search Tree (BST), this results in sorted order.
  • Postorder (Left, Right, Root): Visit the children before the parent. Essential for deleting nodes or calculating directory sizes where you need the sum of children first.
io/thecodeforge/dsa/TreeTraversal.java · JAVA
123456789101112131415161718192021222324252627282930313233
package io.thecodeforge.dsa;

class Node {
    int data;
    Node left, right;
    public Node(int item) { data = item; }
}

public class TreeTraversal {
    // Inorder: Left -> Root -> Right
    public void printInorder(Node node) {
        if (node == null) return;
        printInorder(node.left);
        System.out.print(node.data + " ");
        printInorder(node.right);
    }

    // Preorder: Root -> Left -> Right
    public void printPreorder(Node node) {
        if (node == null) return;
        System.out.print(node.data + " ");
        printPreorder(node.left);
        printPreorder(node.right);
    }

    // Postorder: Left -> Right -> Root
    public void printPostorder(Node node) {
        if (node == null) return;
        printPostorder(node.left);
        printPostorder(node.right);
        System.out.print(node.data + " ");
    }
}
▶ Output
Preorder: 1 2 4 5 3
Inorder: 4 2 5 1 3
Postorder: 4 5 2 3 1
🔥Forge Tip: Stack Frames
Recursion is elegant, but for very deep trees, it can cause a StackOverflowError. In production-grade code, senior engineers often use an explicit java.util.ArrayDeque to implement these traversals iteratively to stay in the Heap and gain better control over memory.
Traversal TypeOrder of VisitPrimary Real-World Use Case
PreorderRoot -> Left -> RightSerialization, creating a copy of the tree, prefix notation.
InorderLeft -> Root -> RightRetrieving sorted data from a Binary Search Tree (BST).
PostorderLeft -> Right -> RootDeleting trees, calculating disk space (bottom-up), postfix notation.

🎯 Key Takeaways

  • Traversals are different 'views' of the same hierarchical data, defined by when the root is visited relative to its children.
  • Inorder = Sorted Order in a BST. If you need to validate if a tree is a BST, an inorder traversal is your best friend.
  • Postorder = Bottom-Up Processing. Use this whenever a parent's value depends on the results of its children (like calculating mathematical expressions or directory sizes).
  • Preorder = Top-Down Processing. Best for tasks where you need to visit the 'summary' or 'parent' before dealing with the details of the children, such as deep-copying a structure.

⚠ Common Mistakes to Avoid

    Forgetting the Base Case
    Symptom

    Recursive traversals result in a StackOverflowError —

    Fix

    Always start your recursive function with a null check: if (node == null) return;.

    Confusing Inorder with Sorted Order
    Symptom

    Assuming Inorder always returns sorted data —

    Fix

    Remember that Inorder only produces sorted output if the underlying structure is a Binary Search Tree (BST). On a general binary tree, it just follows the Left-Root-Right sequence.

    Poor Handling of Skewed Trees
    Symptom

    Performance drops to O(n) space complexity on the stack —

    Fix

    For skewed trees (like a linked list structure), use iterative traversals or tree balancing algorithms like AVL or Red-Black trees.

Interview Questions on This Topic

  • QGiven the Preorder and Inorder sequences of a binary tree, can you reconstruct the unique tree structure? Why isn't Preorder alone sufficient?
  • QHow would you implement a Postorder traversal iteratively using only one stack? Walk through the logic of handling the 'right-child-already-visited' state.
  • QWhy is Postorder traversal used specifically for calculating the size of a directory in a file system?
  • QExplain the space complexity of a recursive tree traversal in both the average case and the worst-case (skewed tree).

Frequently Asked Questions

Which tree traversal is best for deleting a tree?

Postorder traversal is the best choice for deleting a tree. Since you visit the children before the parent, you can safely delete the leaf nodes first and work your way up. If you used preorder, you would lose the references to the children as soon as you deleted the parent node.

Can I perform a tree traversal without using recursion or a stack?

Yes, using Morris Traversal. This algorithm achieves O(1) extra space by temporarily modifying the tree to create 'threads' (links) back to the parent nodes. However, it is rarely used in production because it is complex to implement and temporarily alters the data structure during the process.

What is the difference between Depth-First (DFS) and Breadth-First (BFS) traversal?

DFS (Inorder, Preorder, Postorder) goes as deep as possible down one branch before backtracking. BFS (Level-Order) visits all nodes at the current depth level before moving to the next level. DFS is usually implemented with a Stack (or recursion), while BFS is implemented with a Queue.

How do you do inorder traversal iteratively?

Use an explicit stack. Maintain a pointer 'curr' starting at root. While curr is not None or stack is not empty: push curr and all its left children onto the stack. Pop a node, visit it, then set curr = node.right. This mimics the recursive call stack exactly.

Which traversal produces a sorted list from a BST?

Inorder traversal (Left-Root-Right) of a Binary Search Tree always produces elements in non-decreasing sorted order. This is the defining property of BSTs and the basis of the BST sort algorithm.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousBinary Search TreeNext →Level Order Traversal of Binary Tree
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged