Tree Traversal Level Order BFS in DSA Go - Time & Space Complexity
We want to understand how the time needed to visit all nodes in a tree grows as the tree gets bigger.
How does the number of steps change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
var result [][]int
queue := []*TreeNode{root}
for len(queue) > 0 {
levelSize := len(queue)
var level []int
for i := 0; i < levelSize; i++ {
node := queue[0]
queue = queue[1:]
level = append(level, node.Val)
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
result = append(result, level)
}
return result
}
This code visits each node in a binary tree level by level, from top to bottom, left to right.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node once in the tree.
- How many times: Exactly once per node, as each node is added and removed from the queue once.
As the number of nodes grows, the steps to visit all nodes grow roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The number of steps grows directly with the number of nodes.
Time Complexity: O(n)
This means the time to complete the traversal grows linearly with the number of nodes in the tree.
[X] Wrong: "Since there are nested loops, the time complexity must be quadratic O(n²)."
[OK] Correct: The inner loop runs only for the number of nodes at each level, and all levels combined cover all nodes exactly once, so total work is still linear.
Understanding level order traversal time helps you explain how to efficiently visit all nodes in a tree, a common task in many coding problems.
"What if we used a depth-first search instead of breadth-first search? How would the time complexity change?"