class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; } } class BinaryTree { public Node root; public void TopView() { if (root == null) return; var map = new SortedDictionary<int, int>(); var queue = new Queue<(Node node, int hd)>(); queue.Enqueue((root, 0)); while (queue.Count > 0) { var (node, hd) = queue.Dequeue(); if (!map.ContainsKey(hd)) { 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 val in map.Values) { Console.Write(val + " "); } } } var tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.right = new Node(4); tree.root.left.right.right = new Node(5); tree.root.left.right.right.right = new Node(6); tree.TopView();
The top view prints nodes visible from the top. It uses horizontal distance (hd) from root. The first node at each hd is printed.
Here, nodes at hd -1: 2, hd 0: 1, hd 1: 3, hd 2: 6 appear first.
Horizontal distance is used to track the horizontal position of nodes relative to the root. Left child decreases hd by 1, right child increases hd by 1.
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 val in map.Values) { Console.Write(val + " "); }
The code overwrites the value for each horizontal distance, so the last node at each hd is stored, which corresponds to the bottom view, not top view.
var tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(20); tree.root.right = new Node(30); tree.root.left.left = new Node(40); tree.root.left.right = new Node(50); tree.root.right.left = new Node(60); tree.root.right.right = new Node(70); tree.root.left.right.left = new Node(80); tree.root.left.right.right = new Node(90); tree.TopView();
The top view includes nodes at horizontal distances -2:40, -1:20, 0:10, 1:30, 2:70.
Nodes 50, 60, 80, 90 are hidden behind others when viewed from top.
The sorted dictionary keeps keys (horizontal distances) in ascending order, so when printing, nodes appear from left to right.
