Traversal algorithms are essential for exploring nodes in a binary tree. Here's a breakdown of the most common methods:

1. Pre-order Traversal 📌

  • Definition: Visit root → left subtree → right subtree
  • Steps:
    1. Process the current node
    2. Recursively traverse left subtree
    3. Recursively traverse right subtree
  • Example (Python):
    def pre_order(root):
        if root:
            print(root.val)
            pre_order(root.left)
            pre_order(root.right)
    
pre_order_traversal

2. In-order Traversal 📌

  • Definition: Visit left subtree → root → right subtree
  • Steps:
    1. Recursively traverse left subtree
    2. Process the current node
    3. Recursively traverse right subtree
  • Example (Python):
    def in_order(root):
        if root:
            in_order(root.left)
            print(root.val)
            in_order(root.right)
    
in_order_traversal

3. Post-order Traversal 📌

  • Definition: Visit left subtree → right subtree → root
  • Steps:
    1. Recursively traverse left subtree
    2. Recursively traverse right subtree
    3. Process the current node
  • Example (Python):
    def post_order(root):
        if root:
            post_order(root.left)
            post_order(root.right)
            print(root.val)
    
post_order_traversal

4. Level-order Traversal 📌

  • Definition: Traverse nodes level by level (BFS)
  • Steps:
    1. Use a queue to process nodes
    2. Start from root, enqueue left and right children sequentially
  • Example (Python):
    from collections import deque
    def level_order(root):
        if not root:
            return
        queue = deque([root])
        while queue:
            node = queue.popleft()
            print(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
    
level_order_traversal

For a deeper understanding of binary tree fundamentals, check out our Binary Tree Introduction Guide. 📘