Left Side View of Binary Tree in DSA Go - Time & Space Complexity
We want to understand how the time needed to find the left side view of a binary tree changes as the tree grows.
Specifically, how does the number of steps grow when the tree has more nodes?
Analyze the time complexity of the following code snippet.
func leftSideView(root *TreeNode) []int {
if root == nil {
return []int{}
}
var result []int
queue := []*TreeNode{root}
for len(queue) > 0 {
levelSize := len(queue)
for i := 0; i < levelSize; i++ {
node := queue[0]
queue = queue[1:]
if i == 0 {
result = append(result, node.Val)
}
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
}
return result
}
This code finds the left side view by visiting nodes level by level and recording the first node at each level.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node once in a breadth-first manner.
- How many times: Each node is processed exactly once in the inner loop.
As the number of nodes (n) increases, the code visits each node once, so the total steps grow roughly in direct proportion to n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The number of operations grows linearly with the number of nodes.
Time Complexity: O(n)
This means the time to find the left side view grows directly with the number of nodes in the tree.
[X] Wrong: "Because we only record one node per level, the time is O(height) or less."
[OK] Correct: Even though we record one node per level, we still visit every node to know which is first at each level, so the time depends on total nodes, not just height.
Understanding this helps you explain how tree traversal works and how to analyze algorithms that visit all nodes efficiently.
"What if we changed the traversal to depth-first search instead of breadth-first? How would the time complexity change?"