📖 Scenario: You are working on a program that helps visualize a binary tree from the top. Imagine standing above a tree and looking down. You want to see only the nodes that are visible from this top view, ignoring nodes hidden behind others.
🎯 Goal: Build a Rust program that creates a binary tree, sets up a horizontal distance tracker, computes the top view nodes of the tree, and prints them in order from left to right.
📋 What You'll Learn
Create a binary tree with the exact structure given.
Use a variable to track horizontal distances of nodes.
Implement logic to find the top view nodes of the binary tree.
Print the top view nodes from leftmost to rightmost.
💡 Why This Matters
🌍 Real World
Top view traversal is useful in computer graphics, network routing visualization, and understanding hierarchical data from a specific perspective.
💼 Career
Understanding tree traversals and views is important for software engineers working with data structures, algorithms, and systems that require spatial or hierarchical data processing.
Progress0 / 4 steps
1
Create the Binary Tree Structure
Create a binary tree using the Node struct with the exact structure: root node with value 1, left child 2, right child 3, left child of 2 is 4, right child of 2 is 5, right child of 3 is 6.
DSA Rust
Hint
Use Rc and RefCell to allow multiple ownership and mutability of nodes.
2
Set Up Horizontal Distance Map
Create a mutable HashMap called top_view_map to store the first node value seen at each horizontal distance (key: i32, value: i32).
DSA Rust
Hint
Use HashMap::new() to create an empty map.
3
Implement Top View Logic
Write a recursive function top_view that takes node: Option<Rc<RefCell<Node>>>, hd: i32 (horizontal distance), and mutable reference to top_view_map. It should add the node's value to top_view_map if the horizontal distance is not already present, then recursively call itself for left child with hd - 1 and right child with hd + 1.
DSA Rust
Hint
Check if the horizontal distance is already in the map before inserting. Then recurse left with hd - 1 and right with hd + 1.
4
Print the Top View Nodes
Print the values in top_view_map sorted by their horizontal distance keys from smallest to largest. Use a for loop over sorted keys and print the node values separated by spaces.
DSA Rust
Hint
Sort the keys of top_view_map and print the values in order separated by spaces.
Practice
(1/5)
1. What does the top view of a binary tree represent?
easy
A. Nodes visible when the tree is viewed from the top
B. Nodes visible when the tree is viewed from the left side
C. Nodes visible when the tree is viewed from the bottom
D. Nodes visible when the tree is viewed from the right side
Solution
Step 1: Understand the top view concept
The top view of a binary tree shows all nodes that are visible when looking down vertically from above the tree.
Step 2: Compare with other views
Left, right, and bottom views show nodes visible from those sides, not from the top.
Final Answer:
Nodes visible when the tree is viewed from the top -> Option A
Quick Check:
Top view = nodes seen from above [OK]
Hint: Top view shows nodes visible from above the tree [OK]
Common Mistakes:
Confusing top view with left or right view
Thinking bottom view is the same as top view
2. Which Rust data structure is best suited to store nodes with their horizontal distances for computing the top view of a binary tree?
easy
A. HashMap
B. Vec<Node>
C. LinkedList<Node>
D. BinaryHeap<Node>
Solution
Step 1: Identify the need for horizontal distance mapping
Top view requires tracking nodes by their horizontal distance from the root, which can be negative or positive integers.
Step 2: Choose a data structure for key-value mapping
A HashMap with key as horizontal distance (i32) and value as Node is ideal for quick lookups and updates.
Final Answer:
HashMap -> Option A
Quick Check:
Use HashMap for horizontal distance mapping [OK]
Hint: Use HashMap to map horizontal distance to nodes [OK]
Common Mistakes:
Using Vec which doesn't map keys to values
Using LinkedList which is inefficient for lookups
Using BinaryHeap which is for priority queues
3. Given the following Rust code snippet for top view traversal, what will be printed?
struct Node {
val: i32,
left: Option,
right: Option,
}
// Tree:
// 1
// / \
// 2 3
// \ \
// 4 5
fn main() {
let root = Node {
val: 1,
left: Some(Box::new(Node {
val: 2,
left: None,
right: Some(Box::new(Node { val: 4, left: None, right: None })),
})),
right: Some(Box::new(Node {
val: 3,
left: None,
right: Some(Box::new(Node { val: 5, left: None, right: None })),
})),
};
// Assume top_view function prints top view nodes in order from left to right
top_view(&root);
}
medium
A. [2, 4, 1, 3, 5]
B. [2, 1, 3, 5]
C. [4, 2, 1, 3, 5]
D. [1, 2, 3]
Solution
Step 1: Assign horizontal distances to nodes
Root (1) is at 0, left child (2) at -1, right child (3) at +1, node 4 at 0 (right child of 2), node 5 at +2 (right child of 3).
Step 2: Determine top view nodes by horizontal distance
For each horizontal distance, the first node encountered from top is chosen: -1: 2, 0: 1, +1: 3, +2: 5. Node 4 at 0 is below 1, so ignored.
Final Answer:
[2, 1, 3, 5] -> Option B
Quick Check:
Top view nodes by horizontal distance = [2, 1, 3, 5] [OK]
Hint: Pick first node at each horizontal distance from top [OK]
Common Mistakes:
Including nodes below first at same horizontal distance
Ignoring horizontal distances for nodes
Confusing order of output
4. The following Rust code attempts to compute the top view of a binary tree but has a bug. What is the error?
fn top_view(root: &Node) {
let mut map = std::collections::HashMap::new();
let mut queue = std::collections::VecDeque::new();
queue.push_back((root, 0));
while let Some((node, hd)) = queue.pop_front() {
// Insert node if horizontal distance not present
map.entry(hd).or_insert(node.val);
if let Some(left) = &node.left {
queue.push_back((left, hd - 1));
}
if let Some(right) = &node.right {
queue.push_back((right, hd + 1));
}
}
for key in map.keys() {
println!("{}", map[key]);
}
}
medium
A. The code inserts duplicate nodes for same horizontal distance
B. The queue is not initialized properly
C. The map keys are not sorted before printing, so output order is random
D. The code does not handle empty tree (root is None)
Solution
Step 1: Analyze map insertion and printing
The code inserts nodes correctly using or_insert to keep first node per horizontal distance.
Step 2: Check output order
HashMap keys are unordered, so iterating with map.keys() prints nodes in random order, not left to right.
Final Answer:
The map keys are not sorted before printing, so output order is random -> Option C
Quick Check:
Sort keys before printing top view [OK]
Hint: Sort horizontal distances before printing top view [OK]
Common Mistakes:
Assuming HashMap keys are ordered
Ignoring empty tree case (not asked here)
Thinking queue initialization is wrong
5. You want to find the top view of a binary tree but only have the tree nodes and no horizontal distance stored. Which approach correctly computes the top view in Rust?
A) Use a recursive function passing horizontal distance and level, store first node per horizontal distance with smallest level.
B) Use a stack to traverse nodes and store last node per horizontal distance.
C) Traverse the tree in preorder and print nodes as you visit.
D) Use a queue but ignore horizontal distances and print nodes in insertion order.
hard
A. Preorder traversal printing nodes directly
B. Use stack and store last node per horizontal distance
C. Use queue ignoring horizontal distances
D. Use recursion with horizontal distance and level to track top nodes
Solution
Step 1: Understand top view requires horizontal distance and level
Top view needs to know horizontal distance and the vertical level to pick the topmost node at each horizontal distance.
Step 2: Choose approach that tracks horizontal distance and level
Recursive traversal passing horizontal distance and level, storing first node per horizontal distance with smallest level, correctly computes top view.
Final Answer:
Use recursion with horizontal distance and level to track top nodes -> Option D
Quick Check:
Track horizontal distance and level recursively [OK]
Hint: Track horizontal distance and level to find top nodes [OK]
Common Mistakes:
Ignoring horizontal distance in traversal
Using stack without tracking levels
Printing nodes in preorder without filtering
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.