Top View of Binary Tree in DSA Java - 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.
public void topView(Node root) {
if (root == null) return;
Map topViewMap = new TreeMap<>();
Queue> queue = new LinkedList<>();
queue.add(new Pair<>(root, 0));
while (!queue.isEmpty()) {
Pair temp = queue.poll();
Node node = temp.getKey();
int hd = temp.getValue();
if (!topViewMap.containsKey(hd)) {
topViewMap.put(hd, node.data);
}
if (node.left != null) queue.add(new Pair<>(node.left, hd - 1));
if (node.right != null) queue.add(new Pair<>(node.right, hd + 1));
}
for (int val : topViewMap.values()) {
System.out.print(val + " ");
}
}
This code prints the top view of a binary tree by visiting nodes level by level and tracking horizontal distances.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that visits each node once using a queue.
- How many times: Exactly once per node in the tree, so n times for n nodes.
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 directly with the number of nodes in the tree.
[X] Wrong: "The top view requires checking all paths, so it must be more than linear time."
[OK] Correct: The code visits each node only once using a queue, so it does not repeat work or check extra paths multiple times.
Understanding how to analyze tree traversal time helps you explain your approach clearly and confidently in interviews.
"What if we used a recursive approach instead of a queue? How would the time complexity change?"
Practice
top view of a binary tree represent?Solution
Step 1: Understand the top view concept
The top view of a binary tree includes all nodes visible when looking down vertically from above the tree.Step 2: Compare with other views
Left view shows nodes from the left side, right view from the right side, and leaf nodes are only the bottom nodes. So, only top view matches nodes visible from above.Final Answer:
Nodes visible when the tree is viewed from the top -> Option CQuick Check:
Top view = nodes seen from above [OK]
- Confusing top view with left or right view
- Thinking top view includes all leaf nodes
- Assuming top view is the same as level order traversal
Solution
Step 1: Identify traversal method for top view
Top view is usually found using level order traversal, which requires a queue to process nodes level by level.Step 2: Understand role of other data structures
HashMap is used to store horizontal distances but queue is essential to traverse nodes in order. Stack and ArrayList are not suitable for level order traversal.Final Answer:
Queue -> Option DQuick Check:
Level order traversal uses queue [OK]
- Using stack instead of queue for traversal
- Confusing storage with traversal data structure
- Ignoring the need for horizontal distance mapping
1
/ \
2 3
\ \
4 5
\ \
6 7
Solution
Step 1: Assign horizontal distances (HD) to nodes
Root (1) has HD=0, left child (2) HD=-1, right child (3) HD=1. Node 4 is right child of 2, HD=0. Node 5 is right child of 3, HD=2. Node 6 is right child of 4, HD=1. Node 7 is right child of 5, HD=3.Step 2: Select first node at each HD from top to bottom
At HD=-1: 2, HD=0: 1, HD=1: 3, HD=2: 5, HD=3: 7. Nodes 4 and 6 are hidden behind 1 and 3 respectively.Final Answer:
[2, 1, 3, 5, 7] -> Option BQuick Check:
Top view nodes by HD = [2,1,3,5,7] [OK]
- Including nodes hidden behind others at same horizontal distance
- Mixing order of nodes in output
- Ignoring horizontal distance calculation
Map map = new HashMap<>();
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node temp = queue.poll();
int hd = temp.hd;
if (!map.containsKey(hd)) {
map.put(hd, temp.data);
}
if (temp.left != null) {
temp.left.hd = hd - 1;
queue.add(temp.left);
}
if (temp.right != null) {
temp.right.hd = hd + 1;
queue.add(temp.right);
}
}
Solution
Step 1: Check initialization of horizontal distance
The root node's horizontal distance (hd) must be set before adding to queue. Here, root.hd is not initialized, so hd is zero by default or undefined.Step 2: Understand impact of missing hd initialization
Without root.hd set, all subsequent hd calculations are incorrect, leading to wrong top view nodes.Final Answer:
Horizontal distance (hd) is not initialized for root node -> Option AQuick Check:
Root hd must be set before traversal [OK]
- Forgetting to set root.hd = 0
- Using Stack instead of Queue for level order
- Assuming HashMap order is sorted
Solution
Step 1: Understand the need for ordered horizontal distances
Top view nodes must be printed from leftmost (lowest HD) to rightmost (highest HD). HashMap does not maintain order.Step 2: Use TreeMap for sorted keys
TreeMap stores keys in sorted order automatically, so storing HD as keys and node data as values allows ordered traversal for printing.Final Answer:
Use a TreeMap to store horizontal distances and their nodes -> Option AQuick Check:
TreeMap keeps keys sorted for ordered output [OK]
- Using HashMap and expecting sorted output
- Trying to reverse order with stack instead of sorting keys
- Ignoring horizontal distance ordering
Ready to prove it?
Pass the test and this pattern moves unknown
