Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»A Beginner’s Guide to Preorder, Inorder & Postorder Traversals
    Data Structures & Algorithms

    A Beginner’s Guide to Preorder, Inorder & Postorder Traversals

    codeanddebugBy codeanddebug12 May 2025Updated:12 May 2025No Comments4 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    depth first search featured image
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Dive into Depth-First Search (DFS) on binary trees! In this friendly guide, we’ll learn about preorder, inorder, and postorder traversals using simple Python recursion, perfect for LeetCode prep and coding interviews.

    Content:
     [show]
    • Why Tree Traversals Matter
    • Quick Visual: The Binary Tree We’ll Use
    • 1. Preorder Traversal (Root → Left → Right)
      • Intuition & “Why”
      • Recursive Code (Python)
    • 2. Inorder Traversal (Left → Root → Right)
      • Intuition & “Why”
      • Recursive Code (Python)
    • 3. Postorder Traversal (Left → Right → Root)
      • Intuition & “Why”
      • Recursive Code (Python)
    • Putting It All Together
    • Why Recursion Rocks for DFS

    Why Tree Traversals Matter

    Imagine you’re exploring a hidden maze. At each junction, you choose a path, dive deep until you hit a dead end, then backtrack. That’s essentially Depth-First Search (DFS) in action. When our “maze” is a binary tree, DFS gives us three classic ways to visit every node:

    1. Preorder: Visit the root before its subtrees.
    2. Inorder: Visit the root between its left and right subtrees.
    3. Postorder: Visit the root after its subtrees.

    These traversal patterns aren’t just academic, they’re the backbone of many LeetCode challenges (think “Validate BST” or “Serialize/Deserialize Tree”) and are super common in whiteboard interviews.

    Let’s check each one, build up the intuition, and then translate it into clean, recursive Python code.

    Also read about the Python Program to Level Order Traversals in Binary Trees.

    Quick Visual: The Binary Tree We’ll Use

          1
         / \
        2   3
       / \   \
      4   5   6
    • Preorder: visit 1, then traverse left, then right → [1, 2, 4, 5, 3, 6]
    • Inorder: traverse left, visit 1, then right → [4, 2, 5, 1, 3, 6]
    • Postorder: traverse left, then right, visit 1 → [4, 5, 2, 6, 3, 1]

    Keep these sequences in mind as we code!

    1. Preorder Traversal (Root → Left → Right)

    Intuition & “Why”

    • You’re a scout: you capture the root first (mark it visited), then explore deeper on the left branch, then on the right.
    • Great for copying a tree (clone its structure).

    Recursive Code (Python)

    def preorder(root, result):
        if not root:
            return
        # Visit the root
        result.append(root.val)
        # Explore left
        preorder(root.left, result)
        # Explore right
        preorder(root.right, result)
    
    res = []
    preorder(root, res)
    print(res)  # [1, 2, 4, 5, 3, 6]

    2. Inorder Traversal (Left → Root → Right)

    Intuition & “Why”

    • You’re reading a book: you finish the left chapter, then read the root, then tackle the right chapter.
    • In a binary search tree (BST), inorder traversal gives you sorted order, super useful for checking if a tree is a valid BST.

    Recursive Code (Python)

    def inorder(root, result):
        if not root:
            return
        # Explore left
        inorder(root.left, result)
        # Visit the root
        result.append(root.val)
        # Explore right
        inorder(root.right, result)
    
    res = []
    inorder(root, res)
    print(res)  # [4, 2, 5, 1, 3, 6]

    3. Postorder Traversal (Left → Right → Root)

    Intuition & “Why”

    • You’re cleaning the mansion: clean left wing, clean right wing, and finally lock up the main door (root).
    • Perfect for deleting or freeing nodes: you want to handle children before the parent.

    Recursive Code (Python)

    def postorder(root, result):
        if not root:
            return
        # Explore left
        postorder(root.left, result)
        # Explore right
        postorder(root.right, result)
        # Visit the root
        result.append(root.val)
    
    res = []
    postorder(root, res)
    print(res)  # [4, 5, 2, 6, 3, 1]

    Putting It All Together

    Here’s a single class encapsulating all three traversals neatly:

    class DFSBinaryTree:
        def preorder(self, root, res):
            if not root: return
            res.append(root.val)
            self.preorder(root.left, res)
            self.preorder(root.right, res)
    
        def inorder(self, root, res):
            if not root: return
            self.inorder(root.left, res)
            res.append(root.val)
            self.inorder(root.right, res)
    
        def postorder(self, root, res):
            if not root: return
            self.postorder(root.left, res)
            self.postorder(root.right, res)
            res.append(root.val)

    Example:

    traversals = DFSBinaryTree()
    pre, ino, post = [], [], []
    traversals.preorder(root, pre)
    traversals.inorder(root, ino)
    traversals.postorder(root, post)
    
    print("Preorder =", pre)    # [1, 2, 4, 5, 3, 6]
    print("Inorder =", ino)    # [4, 2, 5, 1, 3, 6]
    print("Postorder =", post)   # [4, 5, 2, 6, 3, 1]

    Why Recursion Rocks for DFS

    • Elegance: The call stack naturally tracks which node you came from, no need for manual stacks or markers.
    • Clarity: Each function call focuses on one node, delegating subtrees to deeper calls.
    • Conciseness: A few lines of code handle the entire traversal.
    Master DSA with our course

    For any changes to the document, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Binary Trees
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticlePython Program to Count Number of Digits | Explained
    Next Article Breadth-First Search in Binary Trees: Level-Order Traversal with Python
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Diameter of Binary Tree

    14 May 2025
    Data Structures & Algorithms

    Maximum Depth of Binary Tree | Explained with Examples

    14 May 2025
    Data Structures & Algorithms

    Breadth-First Search in Binary Trees: Level-Order Traversal with Python

    12 May 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (13)
      • Beginner (9)
      • Intermediate (4)
    Recent Posts

    Diameter of Binary Tree

    14 May 2025

    Maximum Depth of Binary Tree | Explained with Examples

    14 May 2025

    Breadth-First Search in Binary Trees: Level-Order Traversal with Python

    12 May 2025

    A Beginner’s Guide to Preorder, Inorder & Postorder Traversals

    12 May 2025

    Python Program to Count Number of Digits | Explained

    12 May 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.