Right Side View of Binary Tree in DSA Go - Time & Space Complexity
We want to understand how the time needed to find the right 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 rightSideView(root *TreeNode) []int {
if root == nil {
return []int{}
}
var result []int
queue := []*TreeNode{root}
for len(queue) > 0 {
size := len(queue)
for i := 0; i < size; i++ {
node := queue[0]
queue = queue[1:]
if i == size-1 {
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 uses a level-by-level traversal to collect the rightmost node's value at each level of the binary tree.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer loop runs while there are nodes to process, and the inner loop visits each node at the current level.
- How many times: Each node in the tree is visited exactly once during the traversal.
As the number of nodes (n) in the tree 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 work grows linearly with the number of nodes.
Time Complexity: O(n)
This means the time to find the right side view grows directly with the number of nodes in the tree.
[X] Wrong: "The time complexity is O(log n) because we only look at one node per level."
[OK] Correct: Even though we record one node per level, we still visit every node to find that rightmost node, so the time depends on all nodes, not just the height.
Understanding this traversal and its time complexity helps you explain how tree algorithms work efficiently, a common skill interviewers look for.
"What if we changed the traversal to a depth-first search instead of breadth-first? How would the time complexity change?"