Browse curriculum

Types of DFS (Tree Traversals)

Types of DFS (Tree Traversals): master Preorder, Inorder, and Postorder traversals: the building blocks of most Tree algorithms.

Medium
15 min
Solve on LeetCode

The Three Flavors of DFS

When traversing a Tree using Depth-First Search, the "depth-first" logic remains the same (go down before going sideways). However, the order in which we "process" (visit/print) the current node relative to its children defines the three main types:

  1. Preorder: Root → Left → Right
  2. Inorder: Left → Root → Right
  3. Postorder: Left → Right → Root

Problem: Standardize the Visit

Given a binary tree, return a list of values depending on the traversal order.

  • Input: Tree [1, null, 2, 3] (1 is root, 2 is right child, 3 is left child of 2)
  • Preorder Output: [1, 2, 3]
  • Inorder Output: [1, 3, 2]
  • Postorder Output: [3, 2, 1]

When to use each type?

Pattern Recognition:

  • Preorder: Creating a copy of the tree, Prefix expression evaluation, Serialization.
  • Inorder: Binary Search Tree (BST) validation (gives sorted order), Infix expression.
  • Postorder: Deleting a tree (delete children before parent), Postfix evaluation, Computing height/size (need child info first).

Intuition: The Tour Route

Imagine tracing the outline of the tree starting from the left of the root.

  • Preorder: Snap a photo the moment you arrive at a node for the first time.
  • Inorder: Snap a photo only after you've returned from the left child but before going right.
  • Postorder: Snap a photo only when you are leaving the node for the last time (finished both children).

Visualizing the Stack

NODE · LEFT · RIGHT

ENTER

Stack depth

1

Appended

0

call stack

preorder(4)

result

Nothing appended yet

 

preorder(4)

Next

Preorder visits before either child: append 4. result = [4]

Free preview: the first 13 of 43 steps

Tree

Pick an order and run it. The walk is the same in all three (the outlined calls go down and come back up along the same path) and only the step where a node is appended moves. Each node shows the order it was appended in; switch orders on the same tree and watch the numbers change.

Dry Run Comparison

Tree: Root(1) -> Left(2), Right(3).

Step Preorder (Root-L-R) Inorder (L-Root-R) Postorder (L-R-Root)
1 Visit 1. Go Left(2). Go Left(2). Go Left(2).
2 Visit 2. Go Left(null). Go Left(null). Visit 2. Go Left(null). Go Right(null).
3 Back to 2. Go Right(null). Back to 2. Go Right. Back to 2. Visit 2. Return.
4 Back to 1. Go Right(3). Visit 1. Go Right(3). Back to 1. Go Right(3).
5 Visit 3. Children null. Left null. Visit 3. Left null. Right null. Visit 3.
6 Done. Done. Back to 1. Visit 1. Done.

The Code Templates

The three methods are identical except for one line: where result gets the node: before both calls, between them, or after both.

Types of DFS (Tree Traversals) Code
1function preorder(node, result) {
2 if (!node) return;
3 result.push(node.val);
4 preorder(node.left, result);
5 preorder(node.right, result);
6}
7
8function inorder(node, result) {
9 if (!node) return;
10 inorder(node.left, result);
11 result.push(node.val);
12 inorder(node.right, result);
13}
14
15function postorder(node, result) {
16 if (!node) return;
17 postorder(node.left, result);
18 postorder(node.right, result);
19 result.push(node.val);
20}

Types of DFS (Tree Traversals) in Python, Java, C++, TypeScript and C

Types of DFS (Tree Traversals) in Python
class Solution:
    def preorder(self, node, result):
        if not node:
            return
        result.append(node.val)
        self.preorder(node.left, result)
        self.preorder(node.right, result)

    def inorder(self, node, result):
        if not node:
            return
        self.inorder(node.left, result)
        result.append(node.val)
        self.inorder(node.right, result)

    def postorder(self, node, result):
        if not node:
            return
        self.postorder(node.left, result)
        self.postorder(node.right, result)
        result.append(node.val)
Types of DFS (Tree Traversals) in Java
class Solution {
    void preorder(TreeNode node, List<Integer> result) {
        if (node == null) return;
        result.add(node.val);
        preorder(node.left, result);
        preorder(node.right, result);
    }

    void inorder(TreeNode node, List<Integer> result) {
        if (node == null) return;
        inorder(node.left, result);
        result.add(node.val);
        inorder(node.right, result);
    }

    void postorder(TreeNode node, List<Integer> result) {
        if (node == null) return;
        postorder(node.left, result);
        postorder(node.right, result);
        result.add(node.val);
    }
}
Types of DFS (Tree Traversals) in C++
class Solution {
public:
    void preorder(TreeNode* node, vector<int>& result) {
        if (!node) return;
        result.push_back(node->val);
        preorder(node->left, result);
        preorder(node->right, result);
    }

    void inorder(TreeNode* node, vector<int>& result) {
        if (!node) return;
        inorder(node->left, result);
        result.push_back(node->val);
        inorder(node->right, result);
    }

    void postorder(TreeNode* node, vector<int>& result) {
        if (!node) return;
        postorder(node->left, result);
        postorder(node->right, result);
        result.push_back(node->val);
    }
};
Types of DFS (Tree Traversals) in TypeScript
function preorder(node: TreeNode | null, result: number[]): void {
    if (!node) return;
    result.push(node.val);
    preorder(node.left, result);
    preorder(node.right, result);
}

function inorder(node: TreeNode | null, result: number[]): void {
    if (!node) return;
    inorder(node.left, result);
    result.push(node.val);
    inorder(node.right, result);
}

function postorder(node: TreeNode | null, result: number[]): void {
    if (!node) return;
    postorder(node.left, result);
    postorder(node.right, result);
    result.push(node.val);
}
Types of DFS (Tree Traversals) in C
void preorder(struct TreeNode* node, int* result, int* size) {
    if (node == NULL) return;
    result[(*size)++] = node->val;
    preorder(node->left, result, size);
    preorder(node->right, result, size);
}

void inorder(struct TreeNode* node, int* result, int* size) {
    if (node == NULL) return;
    inorder(node->left, result, size);
    result[(*size)++] = node->val;
    inorder(node->right, result, size);
}

void postorder(struct TreeNode* node, int* result, int* size) {
    if (node == NULL) return;
    postorder(node->left, result, size);
    postorder(node->right, result, size);
    result[(*size)++] = node->val;
}

Iterative Approaches (Stack)

Using the call stack (recursion) is elegant, but sometimes we need to simulate it manually using an explicit stack.

  • Preorder: Push Root. While stack: Pop, process, push Right, push Left.
  • Inorder: Push all left nodes. Pop, process, move Right, repeat.
  • Postorder: Tricky (Use 2 stacks or reverse Preorder Root-Right-Left).

Edge Cases & Checks

Standard tree checks apply:

  • Empty Tree: Root is null. Return empty list.

  • Single Node: Left/Right are null. Recursion handles this (base case).

  • Skewed Tree: Effectively a Linked List. Recursion depth might hit limits (O(N)).

Summary

Recap:

  • Preorder: Root first.
  • Inorder: Root middle (Sorted for BST).
  • Postorder: Root last (Bottom-up processing).

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Walk the same path

    Return at an empty node, then recurse left and right.

  2. Choose when to append

    Append before both calls for preorder, between them for inorder, or after both for postorder.

  3. Collect the result

    The appended values, in order, are the traversal.

Frequently asked questions

What is the difference between preorder, inorder and postorder?

They follow the same path through the tree and differ only in when a node is processed: before its children (preorder), between them (inorder), or after both (postorder).


Why does inorder traversal of a BST come out sorted?

Everything in a node's left subtree is smaller and everything in its right subtree is larger, so visiting left, then the node, then right lists the values in increasing order.


When is postorder the right choice?

When a node's answer depends on its children's answers, such as height, subtree sums or deleting a tree: the children must be finished first.


Can you reconstruct a binary tree from its traversals?

Yes, combining inorder with either preorder or postorder uniquely reconstructs any binary tree with distinct values. Inorder separates the left and right subtrees, while preorder or postorder identifies the root.


What is the time and space complexity of DFS tree traversals?

All three traversals run in O(n) time since every node is visited exactly once, and O(h) auxiliary space where h is the tree height, bounded by the recursion stack.

New to the technique behind this problem? Watch it run step by step:

Depth First Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description