0
0
DSA Typescriptprogramming~30 mins

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

Choose your learning style9 modes available
Top View of Binary Tree
📖 Scenario: You are working with a binary tree, a structure like a family tree but with each person having at most two children. You want to see the tree from the top, like looking down from above, so you only see the nodes that are visible without any others blocking them.
🎯 Goal: Build a program that finds the top view of a binary tree. The top view shows the nodes visible when the tree is seen from above, ordered from left to right.
📋 What You'll Learn
Create a binary tree with the exact structure given
Use a variable to track horizontal distances from the root
Implement a function to find the top view of the binary tree
Print the top view nodes in order from left to right
💡 Why This Matters
🌍 Real World
Top view of a binary tree helps in network routing, city planning, and understanding hierarchical data from a unique perspective.
💼 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
Create a class called Node with properties data (number), left (Node or null), and right (Node or null). Then create the binary tree with root node root having value 1, left child 2, right child 3, left child of 2 as 4, and right child of 2 as 5.
DSA Typescript
Hint

Think of each Node as a person in a family tree with two children. Create the root first, then add children step by step.

2
Set Up Horizontal Distance Map
Create a Map called topViewMap to store the first node data seen at each horizontal distance from the root. Also create a queue array called queue to hold pairs of Node and their horizontal distance (number). Initialize queue with the root node and horizontal distance 0.
DSA Typescript
Hint

Use a Map to remember the first node at each horizontal distance. Use a queue to explore nodes level by level.

3
Implement Top View Logic
Write a while loop that runs while queue.length > 0. Inside, remove the first element from queue into current. If topViewMap does not have current.hd, set it with current.node.data. Then, if current.node.left exists, add it to queue with horizontal distance current.hd - 1. If current.node.right exists, add it to queue with horizontal distance current.hd + 1.
DSA Typescript
Hint

Use a queue to visit nodes in order. For each horizontal distance, keep only the first node you see.

4
Print the Top View
Create an array sortedKeys from topViewMap.keys() and sort it numerically. Then use a for loop over sortedKeys to print the corresponding node data from topViewMap separated by spaces.
DSA Typescript
Hint

Sort the horizontal distances and print the stored node values in that order separated by spaces.