0
0
DSA Goprogramming~30 mins

Top View of Binary Tree in DSA Go - Build from Scratch

Choose your learning style9 modes available
Top View of Binary Tree
📖 Scenario: Imagine you have a tree of family members, and you want to see who is visible if you look from the top. Some members might be hidden behind others. We will find the top view of a binary tree, which means the nodes visible when looking from above.
🎯 Goal: Build a program that creates a binary tree, sets a horizontal distance limit, finds 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 exact nodes and structure
Use a variable to track horizontal distance
Implement logic to find the top view of the binary tree
Print the top view nodes in order
💡 Why This Matters
🌍 Real World
Top view of a binary tree helps in visualizing hierarchical data from a specific perspective, useful in network routing, organizational charts, and graphical rendering.
💼 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 struct called Node with data int, left *Node, and right *Node. Then create the binary tree with root node having data 1, left child 2, right child 3, left child of 2 as 4, and right child of 2 as 5.
DSA Go
Hint

Define the Node struct first, then create nodes and link them as left and right children.

2
Add a map to track horizontal distances
Create a variable called topViewMap of type map[int]int to store the first node data at each horizontal distance. Also create a variable minHD and set it to 0, and maxHD and set it to 0 to track the minimum and maximum horizontal distances.
DSA Go
Hint

Use make to create the map and initialize minHD and maxHD to zero.

3
Implement the top view traversal logic
Write a function topView that takes root *Node, hd int, topViewMap map[int]int, and pointers to minHD and maxHD. Traverse the tree recursively. If hd is not in topViewMap, add root.data. Update minHD and maxHD accordingly. Call topView for left child with hd-1 and right child with hd+1. Call this function from main with hd=0.
DSA Go
Hint

Use recursion to visit nodes. Store the first node at each horizontal distance. Update min and max horizontal distances.

4
Print the top view nodes from left to right
Use a for loop from minHD to maxHD inclusive. Print the values from topViewMap for each horizontal distance separated by spaces.
DSA Go
Hint

Loop from minHD to maxHD and print the values from the map with spaces.