Bird
Raised Fist0
DSA C#programming~30 mins

Top View of Binary Tree in DSA C# - Build from Scratch

Choose your learning style10 modes available
Top View of Binary Tree
📖 Scenario: You are working on a program that helps visualize a binary tree from the top. Imagine standing above a tree and looking down to see which nodes are visible without any nodes blocking others.
🎯 Goal: Build a program that finds and prints the top view of a binary tree. The top view shows the nodes visible when the tree is seen from above, from left to right.
📋 What You'll Learn
Create a binary tree with given nodes and structure
Use a dictionary to track the first node at each horizontal distance
Traverse the tree using level order traversal with horizontal distances
Print the top view nodes from leftmost to rightmost horizontal distance
💡 Why This Matters
🌍 Real World
Top view of a binary tree helps in visualizing hierarchical data structures from a different perspective, useful in graphics, network routing, and organizational charts.
💼 Career
Understanding tree traversals and views is important for software engineers working with data structures, algorithms, and system design.
Progress0 / 4 steps
1
Create the Binary Tree Structure
Create a class called Node with an int field data, and two Node fields called left and right. Then create a binary tree with root node having data = 1, left child with data = 2, and right child with data = 3. Also add left child of node 2 with data = 4 and right child of node 2 with data = 5.
DSA C#
Hint

Define a Node class with data, left, and right. Then create the root and its children as described.

2
Set Up a Dictionary to Track Horizontal Distances
Create a Dictionary<int, int> called topViewMap to store the first node's data at each horizontal distance. Also create a Queue<(Node node, int hd)> called queue to help with level order traversal. Enqueue the root node with horizontal distance 0.
DSA C#
Hint

Use a dictionary to store horizontal distance and node data. Use a queue to hold nodes with their horizontal distances for traversal.

3
Traverse the Tree and Fill the Dictionary
Use a while loop to process nodes in queue. For each node and its horizontal distance hd, if hd is not in topViewMap, add the node's data to topViewMap. Then enqueue the left child with hd - 1 and the right child with hd + 1 if they exist.
DSA C#
Hint

Use a queue to visit nodes level by level. Add the first node you see at each horizontal distance to the dictionary.

4
Print the Top View Nodes from Left to Right
Sort the keys of topViewMap and print the corresponding node data in order, separated by spaces.
DSA C#
Hint

Sort the horizontal distances and print the node data in that 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 right side
D. All leaf nodes of the tree

Solution

  1. Step 1: Understand the top view concept

    The top view of a binary tree includes all nodes visible when looking down from above the tree.
  2. Step 2: Differentiate from other views

    Left or right views show nodes from side angles, while top view shows nodes from above.
  3. Final Answer:

    Nodes visible when the tree is viewed from the top -> Option A
  4. 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 side views
  • Thinking top view includes all leaf nodes
  • Assuming top view shows all nodes in the tree
2. Which of the following C# code snippets correctly declares a node class for a binary tree used in top view calculation?
easy
A. public class Node { public int data; public Node left, right; public Node(int val) { data = val; left = right = null; } }
B. class Node { int data; Node left, right; Node(int val) { data = val; left = right = null; } }
C. public struct Node { public int data; public Node left, right; public Node(int val) { data = val; left = right = null; } }
D. public class Node { int data; Node left, right; Node() { data = 0; left = right = null; } }

Solution

  1. Step 1: Check access modifiers and constructor

    public class Node { public int data; public Node left, right; public Node(int val) { data = val; left = right = null; } } uses public class, public fields, and a constructor with parameter, which is correct for node definition.
  2. Step 2: Identify issues in other options

    class Node { int data; Node left, right; Node(int val) { data = val; left = right = null; } } lacks access modifiers (default private), public struct Node { public int data; public Node left, right; public Node(int val) { data = val; left = right = null; } } uses struct which is not typical for tree nodes, public class Node { int data; Node left, right; Node() { data = 0; left = right = null; } } lacks constructor parameter and fields are private.
  3. Final Answer:

    public class Node { public int data; public Node left, right; public Node(int val) { data = val; left = right = null; } } -> Option A
  4. Quick Check:

    Public class with constructor and public fields = public class Node { public int data; public Node left, right; public Node(int val) { data = val; left = right = null; } } [OK]
Hint: Use public class with constructor and public fields for nodes [OK]
Common Mistakes:
  • Omitting public access modifiers causing inaccessible fields
  • Using struct instead of class for nodes
  • Not initializing left and right to null
3. Consider the following binary tree:
        1
       / \
      2   3
       \   \
        4   5
         \
          6

What is the top view of this tree?
medium
A. [2, 1, 3, 6]
B. [1, 2, 4, 6, 5]
C. [2, 1, 3, 5]
D. [1, 2, 3, 4, 5, 6]

Solution

  1. 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 (right of 2) HD=0, node 5 (right of 3) HD=2, node 6 (right of 4) HD=1.
  2. Step 2: Select topmost nodes at each HD

    Using BFS order, first node at each HD: HD -1: 2, HD 0: 1 (4 hidden below), HD 1: 3 (6 hidden below), HD 2: 5. Sorted by HD: [2, 1, 3, 5]
  3. Final Answer:

    [2, 1, 3, 5] -> Option C
  4. Quick Check:

    Top view nodes by HD = [2, 1, 3, 5] [OK]
Hint: Track horizontal distances and pick first node at each HD [OK]
Common Mistakes:
  • Ignoring horizontal distances and picking all nodes
  • Confusing top view with level order traversal
  • Missing nodes with same horizontal distance but different levels
4. The following C# code attempts to print the top view of a binary tree but has a bug. What is the error?
void PrintTopView(Node root) {
  if (root == null) return;
  var map = new Dictionary<int, int>();
  var queue = new Queue<(Node node, int hd)>();
  queue.Enqueue((root, 0));
  while (queue.Count > 0) {
    var (node, hd) = queue.Dequeue();
    map[hd] = node.data;
    if (node.left != null) queue.Enqueue((node.left, hd - 1));
    if (node.right != null) queue.Enqueue((node.right, hd + 1));
  }
  foreach (var key in map.Keys.OrderBy(k => k)) {
    Console.Write(map[key] + " ");
  }
}
medium
A. It does not check for null root
B. It does not enqueue the root node
C. It uses a queue instead of a stack
D. It overwrites nodes at the same horizontal distance instead of keeping the first

Solution

  1. Step 1: Analyze map update logic

    The code assigns map[hd] = node.data every time, overwriting previous entries at the same horizontal distance.
  2. Step 2: Understand top view requirement

    Top view requires the first node encountered at each horizontal distance, so overwriting causes incorrect output.
  3. Final Answer:

    It overwrites nodes at the same horizontal distance instead of keeping the first -> Option D
  4. Quick Check:

    Keep first node per HD, not overwrite [OK]
Hint: Store node only if HD not already in map [OK]
Common Mistakes:
  • Overwriting map entries for horizontal distances
  • Ignoring null root check (though present here)
  • Confusing queue with stack usage
5. You want to find the top view of a binary tree but only have access to its inorder and level order traversals:
Inorder: [4, 2, 5, 1, 6, 3, 7]
Level order: [1, 2, 3, 4, 5, 6, 7]

Which approach is best to find the top view?
hard
A. Use level order traversal directly to get top view
B. Reconstruct the tree from traversals, then perform top view traversal
C. Use inorder traversal directly to get top view
D. Top view cannot be found from these traversals

Solution

  1. Step 1: Understand traversal information

    Inorder and level order traversals can be used together to reconstruct the binary tree uniquely.
  2. Step 2: Apply top view after reconstruction

    Once the tree is rebuilt, perform a top view traversal using horizontal distances and BFS.
  3. Final Answer:

    Reconstruct the tree from traversals, then perform top view traversal -> Option B
  4. Quick Check:

    Rebuild tree first, then find top view [OK]
Hint: Rebuild tree from traversals before top view [OK]
Common Mistakes:
  • Trying to get top view directly from inorder or level order
  • Assuming top view is same as level order
  • Believing top view cannot be found from given traversals
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard