0
0
DSA Goprogramming~5 mins

Bottom View of Binary Tree in DSA Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Bottom View of Binary Tree
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the number of nodes (n) increases, the loop runs once for each node.

Input Size (n)Approx. Operations
10About 10 visits and updates
100About 100 visits and updates
1000About 1000 visits and updates

Pattern observation: The work grows directly with the number of nodes; doubling nodes roughly doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the bottom view grows linearly with the number of nodes in the tree.

Common Mistake

[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.

Interview Connect

Understanding this linear time complexity helps you explain efficient tree traversals and map usage clearly, a skill valued in many coding challenges.

Self-Check

"What if we used a depth-first search instead of breadth-first search? How would the time complexity change?"