Top View of Binary Tree in DSA Go - Time & Space Complexity
We want to understand how the time needed to find the top view of a binary tree changes as the tree grows.
How does the number of nodes affect the work done to get the top view?
Analyze the time complexity of the following code snippet.
func topView(root *Node) []int {
if root == nil {
return []int{}
}
type pair struct {
node *Node
hd int
}
queue := []pair{{root, 0}}
hdMap := map[int]int{}
minHd, maxHd := 0, 0
for len(queue) > 0 {
p := queue[0]
queue = queue[1:]
if _, ok := hdMap[p.hd]; !ok {
hdMap[p.hd] = p.node.data
}
if p.node.left != nil {
queue = append(queue, pair{p.node.left, p.hd - 1})
if p.hd-1 < minHd {
minHd = p.hd - 1
}
}
if p.node.right != nil {
queue = append(queue, pair{p.node.right, p.hd + 1})
if p.hd+1 > maxHd {
maxHd = p.hd + 1
}
}
}
result := []int{}
for i := minHd; i <= maxHd; i++ {
result = append(result, hdMap[i])
}
return result
}
This code finds the top view of a binary tree by doing a level order traversal and tracking horizontal distances.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that processes each node once in a queue.
- How many times: Exactly once per node in the tree (n times).
As the number of nodes grows, the code visits each node once, so the work grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits and checks |
| 100 | About 100 visits and checks |
| 1000 | About 1000 visits and checks |
Pattern observation: The operations increase linearly as the tree size increases.
Time Complexity: O(n)
This means the time to find the top view grows in direct proportion to the number of nodes in the tree.
[X] Wrong: "The code visits nodes multiple times, so the time is more than linear."
[OK] Correct: Each node is added to the queue once and processed once, so the total work is proportional to the number of nodes.
Understanding this linear time complexity helps you explain how tree traversals work efficiently and shows you can analyze common tree problems clearly.
"What if we used a depth-first traversal instead of breadth-first? How would the time complexity change?"