tree traversal
depth-first search
computer science
algorithms
data structures

Walking a tree, parent first

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Walking a tree parent first means visiting each node before any of its children. In binary-tree terminology, this is preorder traversal, and it is useful when the parent node contains information you need to process before deciding how to handle the descendants.

What Parent-First Traversal Means

For each node, the order is:

  1. visit the current node
  2. traverse the first child subtree
  3. traverse the remaining child subtrees

In a binary tree, that usually means “node, left, right.”

python
1class Node:
2    def __init__(self, value, left=None, right=None):
3        self.value = value
4        self.left = left
5        self.right = right

Recursive Preorder Traversal

The recursive version is the clearest starting point.

python
1def preorder(node):
2    if node is None:
3        return
4
5    print(node.value)
6    preorder(node.left)
7    preorder(node.right)
8
9root = Node("A", Node("B", Node("D"), Node("E")), Node("C"))
10preorder(root)

Output:

text
1A
2B
3D
4E
5C

That output shows the parent is processed before each child subtree.

Why Parent-First Is Useful

Parent-first traversal is natural when the parent node determines context for its descendants. Examples include:

  • serializing a tree structure
  • copying a tree
  • printing directory-like hierarchies
  • evaluating or exporting syntax trees in prefix-like form

If your logic depends on setting up state before visiting children, preorder is often the right traversal.

Iterative Version with a Stack

Recursion is elegant, but an explicit stack is useful when you want tighter control or want to avoid deep recursion.

python
1def preorder_iterative(root):
2    if root is None:
3        return
4
5    stack = [root]
6    while stack:
7        node = stack.pop()
8        print(node.value)
9
10        if node.right is not None:
11            stack.append(node.right)
12        if node.left is not None:
13            stack.append(node.left)
14
15preorder_iterative(root)

The right child is pushed first so the left child is processed first when popped from the stack.

General Trees with Many Children

For a general tree, parent-first still means visiting the current node before iterating over its children.

python
1class TreeNode:
2    def __init__(self, value, children=None):
3        self.value = value
4        self.children = children or []
5
6def walk_parent_first(node):
7    if node is None:
8        return
9
10    print(node.value)
11    for child in node.children:
12        walk_parent_first(child)

This pattern works for menus, organization charts, DOM-like structures, and many other hierarchical datasets.

Compare with Other Traversals

It helps to distinguish preorder from the other common traversals.

  • preorder: parent before children
  • inorder: left subtree, parent, right subtree
  • postorder: children before parent

If the requirement literally says “parent first,” preorder is the intended answer. Choosing inorder or postorder changes the semantic meaning of the walk.

Time and Space Complexity

Parent-first traversal visits each node exactly once, so time complexity is O(n). The extra space is O(h) for recursion or the explicit stack, where h is the tree height. On very unbalanced trees, the recursion depth can approach the number of nodes.

Common Pitfalls

A common mistake is describing preorder traversal correctly but then writing code that prints the parent after recurring into a child. Another is forgetting the base case for None, which causes runtime errors in recursive code. Developers also sometimes push the left child before the right child in the iterative version and then wonder why the output order is reversed. Finally, if the tree can be very deep, the recursive version may hit recursion limits and should be replaced with an explicit stack.

Summary

  • Parent-first traversal is preorder traversal.
  • In a binary tree, the order is current node, left subtree, right subtree.
  • Recursion is the simplest implementation, but a stack-based version is easy too.
  • Use parent-first traversal when the parent provides context needed before visiting children.
  • Check the visit order carefully, because one misplaced line changes the traversal semantics completely.

Course illustration
Course illustration

All Rights Reserved.