7.2 Traversing a binary tree¶
In its physical representation, a tree is a linked data structure, so traversal follows pointers from node to node. Unlike a linked list, however, a tree is nonlinear. Traversing it is more complex and requires a search algorithm.
Common binary-tree traversals include level-order, preorder, inorder, and postorder traversal.
7.2.1 Level-order traversal¶
As shown below, level-order traversal visits the tree level by level from top to bottom, moving from left to right within each level.
Level-order traversal is a form of breadth-first traversal, also called breadth-first search (BFS). It explores outward one layer at a time.
Figure 7-9 Level-order traversal of a binary tree
Description of Figure 7-9: Level-order traversal of a binary tree
Visit the tree level by level from top to bottom, moving from left to right within each level.
The example has 7 nodes in three levels. Root 1 has children 2 and 3, node 2 has children 4 and 5, and node 3 has children 6 and 7, each listed from left to right. Nodes 4, 5, 6, and 7 are leaves.
| Level | Nodes from left to right |
|---|---|
| 1 | 1 |
| 2 | 2, 3 |
| 3 | 4, 5, 6, 7 |
After nodes 2 and 3 on level 2, traversal moves to the leftmost node 4 on level 3. That is why 4 follows 3. Solid gray arrows show parent–child links. Dashed arrows through the blue dots below the nodes show only visit order. The diagonal 3→4 arrow crosses levels, while 4’s parent remains 2.
The level-order sequence is [1, 2, 3, 4, 5, 6, 7]. Each node is visited exactly once.
1. Implementation¶
Breadth-first traversal usually uses a queue. A queue's first-in, first-out rule matches the traversal's level-by-level progression. The implementation follows:
def level_order(root: TreeNode | None) -> list[int]:
"""Level-order traversal"""
# Initialize a queue and enqueue the root
queue: deque[TreeNode] = deque()
queue.append(root)
# Initialize a list to store the traversal sequence
res = []
while queue:
node: TreeNode = queue.popleft() # Dequeue from the queue
res.append(node.val) # Store the node value
if node.left is not None:
queue.append(node.left) # Enqueue the left child
if node.right is not None:
queue.append(node.right) # Enqueue the right child
return res
/* Level-order traversal */
vector<int> levelOrder(TreeNode *root) {
// Initialize a queue and enqueue the root
queue<TreeNode *> queue;
queue.push(root);
// Initialize a list to store the traversal sequence
vector<int> vec;
while (!queue.empty()) {
TreeNode *node = queue.front();
queue.pop(); // Dequeue from the queue
vec.push_back(node->val); // Store the node value
if (node->left != nullptr)
queue.push(node->left); // Enqueue the left child
if (node->right != nullptr)
queue.push(node->right); // Enqueue the right child
}
return vec;
}
/* Level-order traversal */
List<Integer> levelOrder(TreeNode root) {
// Initialize a queue and enqueue the root
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
// Initialize a list to store the traversal sequence
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll(); // Dequeue from the queue
list.add(node.val); // Store the node value
if (node.left != null)
queue.offer(node.left); // Enqueue the left child
if (node.right != null)
queue.offer(node.right); // Enqueue the right child
}
return list;
}
/* Level-order traversal */
List<int> LevelOrder(TreeNode root) {
// Initialize a queue and enqueue the root
Queue<TreeNode> queue = new();
queue.Enqueue(root);
// Initialize a list to store the traversal sequence
List<int> list = [];
while (queue.Count != 0) {
TreeNode node = queue.Dequeue(); // Dequeue from the queue
list.Add(node.val!.Value); // Store the node value
if (node.left != null)
queue.Enqueue(node.left); // Enqueue the left child
if (node.right != null)
queue.Enqueue(node.right); // Enqueue the right child
}
return list;
}
/* Level-order traversal */
func levelOrder(root *TreeNode) []any {
// Initialize a queue and enqueue the root
queue := list.New()
queue.PushBack(root)
// Initialize a slice to store the traversal sequence
nums := make([]any, 0)
for queue.Len() > 0 {
// Dequeue from the queue
node := queue.Remove(queue.Front()).(*TreeNode)
// Store the node value
nums = append(nums, node.Val)
if node.Left != nil {
// Enqueue the left child
queue.PushBack(node.Left)
}
if node.Right != nil {
// Enqueue the right child
queue.PushBack(node.Right)
}
}
return nums
}
/* Level-order traversal */
func levelOrder(root: TreeNode) -> [Int] {
// Initialize a queue and enqueue the root
var queue: [TreeNode] = [root]
// Initialize a list to store the traversal sequence
var list: [Int] = []
while !queue.isEmpty {
let node = queue.removeFirst() // Dequeue from the queue
list.append(node.val) // Store the node value
if let left = node.left {
queue.append(left) // Enqueue the left child
}
if let right = node.right {
queue.append(right) // Enqueue the right child
}
}
return list
}
/* Level-order traversal */
function levelOrder(root) {
// Initialize a queue and enqueue the root
const queue = [root];
// Initialize a list to store the traversal sequence
const list = [];
while (queue.length) {
let node = queue.shift(); // Dequeue from the queue
list.push(node.val); // Store the node value
if (node.left) queue.push(node.left); // Enqueue the left child
if (node.right) queue.push(node.right); // Enqueue the right child
}
return list;
}
/* Level-order traversal */
function levelOrder(root: TreeNode | null): number[] {
// Initialize a queue and enqueue the root
const queue = [root];
// Initialize a list to store the traversal sequence
const list: number[] = [];
while (queue.length) {
let node = queue.shift() as TreeNode; // Dequeue from the queue
list.push(node.val); // Store the node value
if (node.left) {
queue.push(node.left); // Enqueue the left child
}
if (node.right) {
queue.push(node.right); // Enqueue the right child
}
}
return list;
}
/* Level-order traversal */
List<int> levelOrder(TreeNode? root) {
// Initialize a queue and enqueue the root
Queue<TreeNode?> queue = Queue();
queue.add(root);
// Initialize a list to store the traversal sequence
List<int> res = [];
while (queue.isNotEmpty) {
TreeNode? node = queue.removeFirst(); // Dequeue from the queue
res.add(node!.val); // Store the node value
if (node.left != null) queue.add(node.left); // Enqueue the left child
if (node.right != null) queue.add(node.right); // Enqueue the right child
}
return res;
}
/* Level-order traversal */
fn level_order(root: &Rc<RefCell<TreeNode>>) -> Vec<i32> {
// Initialize a queue and enqueue the root
let mut que = VecDeque::new();
que.push_back(root.clone());
// Initialize a list to store the traversal sequence
let mut vec = Vec::new();
while let Some(node) = que.pop_front() {
// Dequeue from the queue
vec.push(node.borrow().val); // Store the node value
if let Some(left) = node.borrow().left.as_ref() {
que.push_back(left.clone()); // Enqueue the left child
}
if let Some(right) = node.borrow().right.as_ref() {
que.push_back(right.clone()); // Enqueue the right child
};
}
vec
}
/* Level-order traversal */
int *levelOrder(TreeNode *root, int *size) {
/* Auxiliary queue */
int front, rear;
int index, *arr;
TreeNode *node;
TreeNode **queue;
/* Auxiliary queue */
queue = (TreeNode **)malloc(sizeof(TreeNode *) * MAX_SIZE);
// Queue indices
front = 0, rear = 0;
// Enqueue the root node
queue[rear++] = root;
// Initialize a list to store the traversal sequence
/* Auxiliary array */
arr = (int *)malloc(sizeof(int) * MAX_SIZE);
// Array index
index = 0;
while (front < rear) {
// Dequeue from the queue
node = queue[front++];
// Store the node value
arr[index++] = node->val;
if (node->left != NULL) {
// Enqueue the left child
queue[rear++] = node->left;
}
if (node->right != NULL) {
// Enqueue the right child
queue[rear++] = node->right;
}
}
// Update the array length
*size = index;
arr = realloc(arr, sizeof(int) * (*size));
// Free the auxiliary queue array
free(queue);
return arr;
}
/* Level-order traversal */
fun levelOrder(root: TreeNode?): MutableList<Int> {
// Initialize a queue and enqueue the root
val queue = LinkedList<TreeNode?>()
queue.add(root)
// Initialize a list to store the traversal sequence
val list = mutableListOf<Int>()
while (queue.isNotEmpty()) {
val node = queue.poll() // Dequeue from the queue
list.add(node?._val!!) // Store the node value
if (node.left != null)
queue.offer(node.left) // Enqueue the left child
if (node.right != null)
queue.offer(node.right) // Enqueue the right child
}
return list
}
### Level-order traversal ###
def level_order(root)
# Initialize a queue and enqueue the root
queue = [root]
# Initialize a list to store the traversal sequence
res = []
while !queue.empty?
node = queue.shift # Dequeue from the queue
res << node.val # Store the node value
queue << node.left unless node.left.nil? # Enqueue the left child
queue << node.right unless node.right.nil? # Enqueue the right child
end
res
end
Visualize execution
2. Complexity analysis¶
- Time complexity: \(O(n)\). Each of the \(n\) nodes is visited once, taking \(O(n)\) time.
- Space complexity: \(O(n)\). In the worst case, a perfect binary tree, the queue holds up to \((n + 1) / 2\) nodes just before the lowest level is visited, requiring \(O(n)\) space.
7.2.2 Preorder, inorder, and postorder traversal¶
Preorder, inorder, and postorder traversal are forms of depth-first traversal, also called depth-first search (DFS). They follow a path to its end, then backtrack and continue.
Figure 7-10 illustrates depth-first traversal. Imagine walking once around the outside of the entire binary tree. At each node, you encounter three positions corresponding to preorder, inorder, and postorder visits.
Figure 7-10 Preorder, inorder, and postorder traversal of a binary search tree
Description of Figure 7-10: Three depth-first traversals of a binary tree
Preorder, inorder, and postorder follow the same recursive depth-first path. They differ in when they record the current node.
The caption calls this a binary search tree, but the drawing shows an ordinary binary tree. The left child of root 1 is 2, greater than the root, violating the search tree ordering. Its inorder output is therefore not ascending.
The tree has 7 nodes in three levels. Root 1 has children 2 and 3, node 2 has children 4 and 5, and node 3 has children 6 and 7, each listed from left to right. Nodes 4, 5, 6, and 7 are leaves.
The dashed path around the tree traces recursive calls and returns, distinct from the parent–child edges. An orange dot on the left of each node marks preorder, before left recursion. A blue dot below marks inorder, between the left and right calls. A purple dot on the right marks postorder, after right recursion.
All three traversals recurse left first and right second and return at an empty node. They differ in when the current node is recorded. The table gives the recording point, visit order, and output for each traversal.
| Traversal | When to record the current node | Visit order | Output sequence |
|---|---|---|---|
| Preorder | Before recursing left | Root → left subtree → right subtree | 1, 2, 4, 5, 3, 6, 7 |
| Inorder | After recursing left, before recursing right | Left subtree → root → right subtree | 4, 2, 5, 1, 6, 3, 7 |
| Postorder | After recursing right | Left subtree → right subtree → root | 4, 5, 2, 6, 7, 3, 1 |
1. Implementation¶
Depth-first search is usually implemented recursively:
def pre_order(root: TreeNode | None):
"""Preorder traversal"""
if root is None:
return
# Visit order: root -> left subtree -> right subtree
res.append(root.val)
pre_order(root=root.left)
pre_order(root=root.right)
def in_order(root: TreeNode | None):
"""Inorder traversal"""
if root is None:
return
# Visit order: left subtree -> root -> right subtree
in_order(root=root.left)
res.append(root.val)
in_order(root=root.right)
def post_order(root: TreeNode | None):
"""Postorder traversal"""
if root is None:
return
# Visit order: left subtree -> right subtree -> root
post_order(root=root.left)
post_order(root=root.right)
res.append(root.val)
/* Preorder traversal */
void preOrder(TreeNode *root) {
if (root == nullptr)
return;
// Visit order: root -> left subtree -> right subtree
vec.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
/* Inorder traversal */
void inOrder(TreeNode *root) {
if (root == nullptr)
return;
// Visit order: left subtree -> root -> right subtree
inOrder(root->left);
vec.push_back(root->val);
inOrder(root->right);
}
/* Postorder traversal */
void postOrder(TreeNode *root) {
if (root == nullptr)
return;
// Visit order: left subtree -> right subtree -> root
postOrder(root->left);
postOrder(root->right);
vec.push_back(root->val);
}
/* Preorder traversal */
void preOrder(TreeNode root) {
if (root == null)
return;
// Visit order: root -> left subtree -> right subtree
list.add(root.val);
preOrder(root.left);
preOrder(root.right);
}
/* Inorder traversal */
void inOrder(TreeNode root) {
if (root == null)
return;
// Visit order: left subtree -> root -> right subtree
inOrder(root.left);
list.add(root.val);
inOrder(root.right);
}
/* Postorder traversal */
void postOrder(TreeNode root) {
if (root == null)
return;
// Visit order: left subtree -> right subtree -> root
postOrder(root.left);
postOrder(root.right);
list.add(root.val);
}
/* Preorder traversal */
void PreOrder(TreeNode? root) {
if (root == null) return;
// Visit order: root -> left subtree -> right subtree
list.Add(root.val!.Value);
PreOrder(root.left);
PreOrder(root.right);
}
/* Inorder traversal */
void InOrder(TreeNode? root) {
if (root == null) return;
// Visit order: left subtree -> root -> right subtree
InOrder(root.left);
list.Add(root.val!.Value);
InOrder(root.right);
}
/* Postorder traversal */
void PostOrder(TreeNode? root) {
if (root == null) return;
// Visit order: left subtree -> right subtree -> root
PostOrder(root.left);
PostOrder(root.right);
list.Add(root.val!.Value);
}
/* Preorder traversal */
func preOrder(node *TreeNode) {
if node == nil {
return
}
// Visit order: root -> left subtree -> right subtree
nums = append(nums, node.Val)
preOrder(node.Left)
preOrder(node.Right)
}
/* Inorder traversal */
func inOrder(node *TreeNode) {
if node == nil {
return
}
// Visit order: left subtree -> root -> right subtree
inOrder(node.Left)
nums = append(nums, node.Val)
inOrder(node.Right)
}
/* Postorder traversal */
func postOrder(node *TreeNode) {
if node == nil {
return
}
// Visit order: left subtree -> right subtree -> root
postOrder(node.Left)
postOrder(node.Right)
nums = append(nums, node.Val)
}
/* Preorder traversal */
func preOrder(root: TreeNode?) {
guard let root = root else {
return
}
// Visit order: root -> left subtree -> right subtree
list.append(root.val)
preOrder(root: root.left)
preOrder(root: root.right)
}
/* Inorder traversal */
func inOrder(root: TreeNode?) {
guard let root = root else {
return
}
// Visit order: left subtree -> root -> right subtree
inOrder(root: root.left)
list.append(root.val)
inOrder(root: root.right)
}
/* Postorder traversal */
func postOrder(root: TreeNode?) {
guard let root = root else {
return
}
// Visit order: left subtree -> right subtree -> root
postOrder(root: root.left)
postOrder(root: root.right)
list.append(root.val)
}
/* Preorder traversal */
function preOrder(root) {
if (root === null) return;
// Visit order: root -> left subtree -> right subtree
list.push(root.val);
preOrder(root.left);
preOrder(root.right);
}
/* Inorder traversal */
function inOrder(root) {
if (root === null) return;
// Visit order: left subtree -> root -> right subtree
inOrder(root.left);
list.push(root.val);
inOrder(root.right);
}
/* Postorder traversal */
function postOrder(root) {
if (root === null) return;
// Visit order: left subtree -> right subtree -> root
postOrder(root.left);
postOrder(root.right);
list.push(root.val);
}
/* Preorder traversal */
function preOrder(root: TreeNode | null): void {
if (root === null) {
return;
}
// Visit order: root -> left subtree -> right subtree
list.push(root.val);
preOrder(root.left);
preOrder(root.right);
}
/* Inorder traversal */
function inOrder(root: TreeNode | null): void {
if (root === null) {
return;
}
// Visit order: left subtree -> root -> right subtree
inOrder(root.left);
list.push(root.val);
inOrder(root.right);
}
/* Postorder traversal */
function postOrder(root: TreeNode | null): void {
if (root === null) {
return;
}
// Visit order: left subtree -> right subtree -> root
postOrder(root.left);
postOrder(root.right);
list.push(root.val);
}
/* Preorder traversal */
void preOrder(TreeNode? node) {
if (node == null) return;
// Visit order: root -> left subtree -> right subtree
list.add(node.val);
preOrder(node.left);
preOrder(node.right);
}
/* Inorder traversal */
void inOrder(TreeNode? node) {
if (node == null) return;
// Visit order: left subtree -> root -> right subtree
inOrder(node.left);
list.add(node.val);
inOrder(node.right);
}
/* Postorder traversal */
void postOrder(TreeNode? node) {
if (node == null) return;
// Visit order: left subtree -> right subtree -> root
postOrder(node.left);
postOrder(node.right);
list.add(node.val);
}
/* Preorder traversal */
fn pre_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// Visit order: root -> left subtree -> right subtree
let node = node.borrow();
res.push(node.val);
dfs(node.left.as_ref(), res);
dfs(node.right.as_ref(), res);
}
}
dfs(root, &mut result);
result
}
/* Inorder traversal */
fn in_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// Visit order: left subtree -> root -> right subtree
let node = node.borrow();
dfs(node.left.as_ref(), res);
res.push(node.val);
dfs(node.right.as_ref(), res);
}
}
dfs(root, &mut result);
result
}
/* Postorder traversal */
fn post_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// Visit order: left subtree -> right subtree -> root
let node = node.borrow();
dfs(node.left.as_ref(), res);
dfs(node.right.as_ref(), res);
res.push(node.val);
}
}
dfs(root, &mut result);
result
}
/* Preorder traversal */
void preOrder(TreeNode *root, int *size) {
if (root == NULL)
return;
// Visit order: root -> left subtree -> right subtree
arr[(*size)++] = root->val;
preOrder(root->left, size);
preOrder(root->right, size);
}
/* Inorder traversal */
void inOrder(TreeNode *root, int *size) {
if (root == NULL)
return;
// Visit order: left subtree -> root -> right subtree
inOrder(root->left, size);
arr[(*size)++] = root->val;
inOrder(root->right, size);
}
/* Postorder traversal */
void postOrder(TreeNode *root, int *size) {
if (root == NULL)
return;
// Visit order: left subtree -> right subtree -> root
postOrder(root->left, size);
postOrder(root->right, size);
arr[(*size)++] = root->val;
}
/* Preorder traversal */
fun preOrder(root: TreeNode?) {
if (root == null) return
// Visit order: root -> left subtree -> right subtree
list.add(root._val)
preOrder(root.left)
preOrder(root.right)
}
/* Inorder traversal */
fun inOrder(root: TreeNode?) {
if (root == null) return
// Visit order: left subtree -> root -> right subtree
inOrder(root.left)
list.add(root._val)
inOrder(root.right)
}
/* Postorder traversal */
fun postOrder(root: TreeNode?) {
if (root == null) return
// Visit order: left subtree -> right subtree -> root
postOrder(root.left)
postOrder(root.right)
list.add(root._val)
}
### Preorder traversal ###
def pre_order(root)
return if root.nil?
# Visit order: root -> left subtree -> right subtree
$res << root.val
pre_order(root.left)
pre_order(root.right)
end
### Inorder traversal ###
def in_order(root)
return if root.nil?
# Visit order: left subtree -> root -> right subtree
in_order(root.left)
$res << root.val
in_order(root.right)
end
### Postorder traversal ###
def post_order(root)
return if root.nil?
# Visit order: left subtree -> right subtree -> root
post_order(root.left)
post_order(root.right)
$res << root.val
end
Visualize execution
Tip
Depth-first search can also be implemented iteratively. Interested readers can explore this approach themselves.
Figure 7-11 shows the recursive process for preorder traversal, with two opposing phases: descending into calls and returning from them.
- Descending starts a new function call and visits the next node.
- Returning ends a function call, indicating that the current node has been fully processed.
Figure 7-11 The recursive process of preorder traversal
Description of Figure 7-11: Recursive preorder traversal
Follow a preorder traversal of a 7-node binary tree. Visiting a node adds it to the output. Returning from a call does not.
The binary tree has 7 nodes. Root 1 has children 2 and 3. Node 2 has children 4 and 5, and node 3 has children 6 and 7, listed left to right. Nodes 4, 5, 6, and 7 are leaves.
Preorder visits the root, then the left subtree, then the right subtree. On entering a nonempty node, record its value immediately and recurse into its left and right children in order. A call on an empty subtree returns immediately.
The call path lists active calls from the root to the current node. The 11 steps omit calls on empty subtrees. In 7 steps a node is visited for the first time, and in 4 steps calls return. Steps 4 and 9 return from a left leaf to its parent before entering the right subtree. Steps 6 and 11 return up two levels.
Visit root 1
Start at root 1 and record 1. Call path: 1. Output: [1]. Neither the left subtree (2, 4, 5) nor the right subtree (3, 6, 7) has been visited. Next visit the left child, 2.
Visit left child 2
From 1, visit its left child 2 and record 2. Call path: 1 → 2. Output: [1, 2]. The two leaves under 2 (4 and 5) and the root's right subtree (3, 6, 7) have yet to be visited. Next visit 4.
Visit leaf 4
From 2, visit left leaf 4 and record 4. Call path: 1 → 2 → 4. Output: [1, 2, 4]. The calls on both empty subtrees of 4 return immediately, then control will return to 2. Node 5 and the root's right subtree (3, 6, 7) are still unvisited.
Return from 4 to 2
Leaf 4 is finished. Return to parent 2; the call path is now 1 → 2. Returning records no new node, so the output stays [1, 2, 4]. The left subtree of 2 is complete. Next visit its right child, 5. The root's right subtree (3, 6, 7) is still unvisited.
Visit leaf 5
From 2, visit right leaf 5 and record 5. Call path: 1 → 2 → 5. Output: [1, 2, 4, 5]. Every node in the root's left subtree has been visited, but the calls have yet to return. The calls on the two empty subtrees of 5 return immediately. The root's right subtree (3, 6, 7) is still unvisited.
Return from 5 through 2 to 1
When 5 finishes, return to 2. Both subtrees of 2 are complete, so return again to root 1. The call path is now 1, and the output stays [1, 2, 4, 5]. The root's left subtree is complete. Next enter its unvisited right subtree (3, 6, 7), starting at node 3.
Visit right child 3
From root 1, enter its right child 3 and record 3. Call path: 1 → 3. Output: [1, 2, 4, 5, 3]. The left and right leaves of 3, nodes 6 and 7, are still unvisited. Next visit 6.
Visit leaf 6
From 3, visit left leaf 6 and record 6. Call path: 1 → 3 → 6. Output: [1, 2, 4, 5, 3, 6]. Calls on the two empty subtrees of 6 return immediately, then control will return to 3. Only the right leaf, 7, remains unvisited.
Return from 6 to 3
Leaf 6 is finished. Return to parent 3. The call path is now 1 → 3, and the output stays [1, 2, 4, 5, 3, 6]. The left subtree of 3 is complete. Next visit its remaining right leaf, 7.
Visit leaf 7
From 3, visit right leaf 7 and record 7. Call path: 1 → 3 → 7. The output is complete: [1, 2, 4, 5, 3, 6, 7]. The calls for 7, 3, and 1 still need to return.
Return from 7 through 3 to 1 and finish
After the calls on the empty left and right subtrees of 7 finish, return along 7 → 3 → 1. The call on the root then ends. Every subtree is complete, the call path is empty, and the final output remains [1, 2, 4, 5, 3, 6, 7].
2. Complexity analysis¶
- Time complexity: \(O(n)\). Every node is visited once, taking \(O(n)\) time.
- Space complexity: \(O(n)\). In the worst case, the tree degenerates into a linked list, recursion reaches depth \(n\), and stack frames require \(O(n)\) space.