Module 8 · Trees and Heaps · Lesson 26 of 40

Visiting every node: DFS and BFS

Preorder, inorder and postorder (depth-first), and level order (breadth-first) with a queue.

In this lesson · about 22 minutes

  • Write preorder, inorder and postorder traversals
  • Do a level-order traversal with a queue
  • Choose between DFS and BFS

To traverse a tree means to visit every node once. There are two big families.

Depth-first search (DFS)

Go as deep as you can down one branch before trying the next. There are three orders, depending on when you visit the node itself:

OrderStepsMemory trick
Preordernode, left, rightNode comes pre (before)
Inorderleft, node, rightNode in the middle
Postorderleft, right, nodeNode comes post (after)
def preorder(node, out):
    if node is None:
        return
    out.append(node.value)     # visit
    preorder(node.left, out)
    preorder(node.right, out)

Move the out.append line to get inorder or postorder. Each node is visited once: O(n) time. The call stack goes as deep as the tree is tall: O(h) space.

Breadth-first search (BFS) / level order

Visit the tree level by level, top to bottom, left to right. Use a queue: take a node from the front, visit it, and add its children to the back.

Try it · see it work

Binary search tree and traversals

Pick an order and step through it. Insert a few numbers too. Notice that inorder always comes out sorted in this tree.

20304050607080

Step 1 of 9Inorder = left subtree, then node, then right subtree.

Try it: all four orders

Exercise

Inorder traversal

Write inorder(node) that returns a list of values in left, node, right order.

Code that runs before yours
from collections import deque

class TreeNode:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def build_tree(values):
    """Build a tree from a level-order list such as [1, 2, 3, None, 4]."""
    if not values or values[0] is None:
        return None
    root = TreeNode(values[0])
    queue = deque([root])
    i = 1
    while queue and i < len(values):
        node = queue.popleft()
        if i < len(values) and values[i] is not None:
            node.left = TreeNode(values[i])
            queue.append(node.left)
        i += 1
        if i < len(values) and values[i] is not None:
            node.right = TreeNode(values[i])
            queue.append(node.right)
        i += 1
    return root

Exercise

Level by level

Write levels(root) that returns a list of lists, one per level: [[1], [2, 3], [4, 5]]. Use a queue. Tip: at the start of each level, len(queue) tells you how many nodes are on it.

Code that runs before yours
from collections import deque

class TreeNode:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def build_tree(values):
    """Build a tree from a level-order list such as [1, 2, 3, None, 4]."""
    if not values or values[0] is None:
        return None
    root = TreeNode(values[0])
    queue = deque([root])
    i = 1
    while queue and i < len(values):
        node = queue.popleft()
        if i < len(values) and values[i] is not None:
            node.left = TreeNode(values[i])
            queue.append(node.left)
        i += 1
        if i < len(values) and values[i] is not None:
            node.right = TreeNode(values[i])
            queue.append(node.right)
        i += 1
    return root

Check your understanding0 of 3 correct

Question 1

1.Which order visits left, then the node, then right?

Question 2

2.Which data structure does level-order (BFS) use?

Question 3

3.To delete a whole tree safely (children before parents), which order fits?

Quiz score: 0 of 3

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.