Top View of Binary Tree in DSA Typescript - 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.
Specifically, how the number of nodes affects the work done to get the top view.
Analyze the time complexity of the following code snippet.
function topView(root: TreeNode | null): number[] {
if (!root) return [];
const queue: Array<[TreeNode, number]> = [[root, 0]];
const map = new Map<number, number>();
while (queue.length) {
const [node, hd] = queue.shift()!;
if (!map.has(hd)) map.set(hd, node.val);
if (node.left) queue.push([node.left, hd - 1]);
if (node.right) queue.push([node.right, hd + 1]);
}
return Array.from(map.entries())
.sort((a, b) => a[0] - b[0])
.map(([, val]) => val);
}
This code finds the top view of a binary tree by traversing nodes level by level and tracking horizontal distances.
- Primary operation: The while loop processes each node once using a queue.
- How many times: Exactly once per node, so n times for n nodes.
- Additional operations: Sorting the map entries at the end based on horizontal distance.
As the number of nodes grows, the while loop runs once per node, so operations grow linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 queue operations + sorting ~ 10 log 10 |
| 100 | About 100 queue operations + sorting ~ 100 log 100 |
| 1000 | About 1000 queue operations + sorting ~ 1000 log 1000 |
Pattern observation: The main traversal grows linearly, but sorting adds a small extra cost growing a bit faster than linear.
Time Complexity: O(n log n)
This means the time grows a bit faster than the number of nodes because of the sorting step after visiting all nodes.
[X] Wrong: "The top view can be found in O(n) time without any sorting."
[OK] Correct: We must sort the horizontal distances to output the top view from left to right, which takes O(k log k) time, where k is the number of unique horizontal distances, often proportional to n.
Understanding this complexity helps you explain how tree traversal and sorting combine in real problems, showing your grasp of both data structures and algorithm efficiency.
What if we used a balanced tree or a data structure that keeps keys sorted during insertion? 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 shows nodes visible from the top, ignoring nodes hidden behind others vertically.Step 2: Compare with other views
Left or right views show nodes from sides, and leaf nodes are only the bottom-most nodes, so they differ from top view.Final Answer:
Nodes visible when the tree is viewed from above -> 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 shows all nodes
Solution
Step 1: Identify the need for key-value storage
We need to store nodes with their horizontal distances as keys and node values as values.Step 2: Choose the appropriate data structure
A Map allows storing keys (horizontal distances) with corresponding node values efficiently.Final Answer:
Map (key-value pairs) -> Option AQuick Check:
Use Map for horizontal distance to node mapping [OK]
- Using Array which is index-based, not key-based
- Using Set which stores unique values without keys
- Using Stack which is LIFO, not suitable here
class Node {
constructor(public data: number, public left: Node | null = null, public right: Node | null = null) {}
}
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.right = new Node(4);
root.left.right.right = new Node(5);
root.left.right.right.right = new Node(6);
function topView(root: Node) {
const map = new Map();
const queue: Array<[Node, number]> = [[root, 0]];
while (queue.length) {
const [node, hd] = queue.shift()!;
if (!map.has(hd)) {
map.set(hd, node.data);
}
if (node.left) queue.push([node.left, hd - 1]);
if (node.right) queue.push([node.right, hd + 1]);
}
const sortedKeys = Array.from(map.keys()).sort((a, b) => a - b);
const result = sortedKeys.map(key => map.get(key));
console.log(result);
}
topView(root);Solution
Step 1: Assign horizontal distances and track first nodes
Root(1) at hd=0, left(2) at hd=-1, right(3) at hd=1. Next nodes 4 at hd=0 (ignored, already 1), 5 at hd=1 (ignored, already 3), 6 at hd=2 (new).Step 2: Collect nodes in order of horizontal distance
Sorted keys: -1, 0, 1, 2 with values 2, 1, 3, 6 respectively.Final Answer:
[2, 1, 3, 6] -> Option DQuick Check:
Top view nodes = [2, 1, 3, 6] [OK]
- Including nodes hidden behind others at same horizontal distance
- Not sorting horizontal distances before output
- Adding all nodes instead of first at each horizontal distance
function topView(root: Node) {
const map = new Map();
const queue: Array<[Node, number]> = [[root, 0]];
while (queue.length) {
const [node, hd] = queue.pop()!;
if (!map.has(hd)) {
map.set(hd, node.data);
}
if (node.left) queue.push([node.left, hd - 1]);
if (node.right) queue.push([node.right, hd + 1]);
}
const sortedKeys = Array.from(map.keys()).sort((a, b) => a - b);
const result = sortedKeys.map(key => map.get(key));
console.log(result);
}Solution
Step 1: Analyze queue operation impact
Using pop() removes from end, making traversal depth-first instead of breadth-first, breaking horizontal distance order.Step 2: Correct traversal method
Using shift() removes from front, ensuring level order traversal needed for correct top view.Final Answer:
Using queue.pop() instead of queue.shift() causes wrong traversal order -> Option AQuick Check:
Use shift() for BFS queue [OK]
- Using pop() causing DFS instead of BFS
- Ignoring null root check (less critical here)
- Not sorting keys before output (code does sort)
Solution
Step 1: Understand the problem with duplicates
When nodes share horizontal distance and level, default top view picks first encountered node, not necessarily smallest value.Step 2: Modify map update condition
Update the map only if the new node's value is smaller than the stored value for that horizontal distance to ensure smallest value is shown.Final Answer:
Update the map only if the new node's value is smaller than the existing one at that horizontal distance -> Option BQuick Check:
Keep smallest node value per horizontal distance [OK]
- Ignoring value comparison, keeping first node only
- Using stack breaks level order needed
- Storing all nodes wastes memory and complicates logic
Ready to prove it?
Pass the test and this pattern moves unknown
