Binary Tree
BFS
DFS
Algorithm Complexity
Computational Complexity

Is the runtime of BFS and DFS on a binary tree ON?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

For a binary tree with N nodes, both Breadth-First Search and Depth-First Search run in linear time, written as O(N). The confusion usually comes from mixing runtime with memory complexity, or from applying graph formulas without simplifying for tree structure. The short answer is yes, both traversals are O(N) in time, but they differ in space behavior.

Why Both Traversals Are Linear Time

A full traversal must visit each node at least once, so O(N) is a lower bound. BFS and DFS both reach that lower bound because each node is processed a constant number of times.

BFS work per node:

  • dequeue once
  • inspect up to two children
  • enqueue existing children once

DFS work per node:

  • pop once from stack or enter once in recursion
  • inspect up to two children
  • push or recurse to each child once

Since per-node work is constant and repeated for all nodes, total work scales linearly.

BFS Example with Complexity

BFS explores level by level using a queue.

python
1from collections import deque
2
3class Node:
4    def __init__(self, value, left=None, right=None):
5        self.value = value
6        self.left = left
7        self.right = right
8
9
10def bfs(root):
11    if root is None:
12        return []
13
14    order = []
15    queue = deque([root])
16
17    while queue:
18        node = queue.popleft()
19        order.append(node.value)
20
21        if node.left is not None:
22            queue.append(node.left)
23        if node.right is not None:
24            queue.append(node.right)
25
26    return order

Runtime is O(N) because each node enters and leaves the queue once. Space is O(W), where W is maximum tree width. In a complete tree, width can be proportional to N, so worst-case auxiliary space is O(N).

DFS Example with Complexity

DFS explores one branch deeply before backtracking.

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

Runtime is again O(N) because every node is processed once. Space is O(H), where H is tree height. Balanced trees have height near log N, while skewed trees can have height near N.

Relation to Graph Formula O(V + E)

You may also see traversal complexity expressed as O(V + E) for graphs. That is correct in general. For trees:

  • vertices V = N
  • edges E = N - 1

So O(V + E) becomes O(N + N - 1), which simplifies to O(N). This is why both formulations agree.

Balanced Versus Skewed Trees

Time complexity does not change with shape for full traversal. Space can change a lot.

  • BFS memory grows with width.
  • DFS memory grows with height.

On wide balanced trees, DFS often uses less memory than BFS. On very deep skewed trees, recursive DFS can hit recursion limits, so iterative DFS is safer.

Runnable Example Comparison

Use one test tree and compare outputs.

python
1root = Node(
2    1,
3    left=Node(2, Node(4), Node(5)),
4    right=Node(3, None, Node(6)),
5)
6
7print(bfs(root))          # [1, 2, 3, 4, 5, 6]
8print(dfs_preorder(root)) # [1, 2, 4, 5, 3, 6]

Both functions visit all six nodes once, which matches linear runtime behavior.

Choosing Between BFS and DFS in Practice

Since time complexity is the same for full-tree traversal, choose based on problem requirements.

Use BFS when:

  • you need level-order results
  • you need nearest match by edge distance
  • you need shortest path in an unweighted tree

Use DFS when:

  • you need root-to-leaf path exploration
  • backtracking logic is natural
  • memory pressure from wide levels is a concern

The algorithm choice is often about traversal order and memory profile, not runtime class.

Common Pitfalls

A common pitfall is saying DFS is O(log N) because balanced tree height is log N. That is space intuition, not full traversal runtime. Another mistake is comparing BFS and DFS only on time while ignoring queue and stack growth. Developers also apply tree assumptions directly to arbitrary graphs and forget visited sets, which can lead to repeated processing or infinite loops. Finally, recursive DFS on very deep trees can fail due to recursion depth limits even though asymptotic runtime is still linear.

Summary

  • Yes, BFS and DFS on a binary tree both run in O(N) time.
  • Both traversals process each node a constant number of times.
  • BFS uses O(W) space, DFS uses O(H) space.
  • Graph formula O(V + E) simplifies to O(N) for trees.
  • Choose BFS or DFS based on traversal goals and memory constraints, not runtime class.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.