Bottom View of Binary Tree in DSA Go - Time & Space Complexity
We want to understand how the time needed to find the bottom view of a binary tree changes as the tree grows.
How does the number of nodes affect the work done to get the bottom view?
Analyze the time complexity of the following code snippet.
func bottomView(root *Node) []int {
if root == nil {
return []int{}
}
queue := []Pair{{root, 0}}
hdMap := map[int]int{}
for len(queue) > 0 {
p := queue[0]
queue = queue[1:]
hdMap[p.hd] = p.node.data
if p.node.left != nil {
queue = append(queue, Pair{p.node.left, p.hd - 1})
}
if p.node.right != nil {
queue = append(queue, Pair{p.node.right, p.hd + 1})
}
}
// Extract bottom view from hdMap
return extractBottomView(hdMap)
}
This code uses a breadth-first search to visit each node once, tracking horizontal distances to find the bottom view.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that processes each node in the queue once.
- How many times: Exactly once per node in the tree (n times).
As the number of nodes (n) increases, the loop runs once for each node.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits and updates |
| 100 | About 100 visits and updates |
| 1000 | About 1000 visits and updates |
Pattern observation: The work grows directly with the number of nodes; doubling nodes roughly doubles the work.
Time Complexity: O(n)
This means the time to find the bottom view grows linearly with the number of nodes in the tree.
[X] Wrong: "The time complexity is more than linear because we update the map multiple times for the same horizontal distance."
[OK] Correct: Each node is processed once, and map updates happen inside that single pass, so total operations still scale linearly with nodes.
Understanding this linear time complexity helps you explain efficient tree traversals and map usage clearly, a skill valued in many coding challenges.
"What if we used a depth-first search instead of breadth-first search? How would the time complexity change?"