0
0
DSA Javascriptprogramming~30 mins

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

Choose your learning style9 modes available
Top View of Binary Tree
📖 Scenario: You are working with a binary tree that represents a city skyline from different angles. You want to find the buildings visible when looking from the top.
🎯 Goal: Build a program to find the top view of a binary tree. The top view shows nodes visible when the tree is viewed from above, ignoring nodes hidden behind others.
📋 What You'll Learn
Create a binary tree with nodes having value, left, and right properties
Use a variable topViewMap to store the first node at each horizontal distance
Traverse the tree using a breadth-first search (BFS) 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 understanding which elements are visible from above, useful in graphics, city planning, and network visualization.
💼 Career
Understanding tree traversals and views is important for software engineers working with hierarchical data, UI rendering, and spatial data structures.
Progress0 / 4 steps
1
Create the Binary Tree
Create a binary tree with the root node root having value 1. The root's left child should have value 2 and right child value 3. The left child of node 2 should have value 4, and the right child of node 2 should have value 5. The right child of node 3 should have value 6.
DSA Javascript
Hint

Define a Node class with value, left, and right. Then create nodes and connect them as described.

2
Setup the Map for Top View
Create a variable called topViewMap and set it to an empty JavaScript Map. Also create a queue called queue and initialize it with an array containing an object with node set to root and hd (horizontal distance) set to 0.
DSA Javascript
Hint

Use new Map() for topViewMap. Initialize queue with an object holding node: root and hd: 0.

3
Traverse the Tree and Fill the Map
Use a while loop that runs while queue.length > 0. Inside the loop, remove the first element from queue and store it in current. Extract node and hd from current. If topViewMap does not have hd as a key, set hd in topViewMap to node.value. If node.left exists, push an object with node: node.left and hd: hd - 1 to queue. If node.right exists, push an object with node: node.right and hd: hd + 1 to queue.
DSA Javascript
Hint

Use a while loop with queue.shift() to get current node and horizontal distance. Add to topViewMap only if hd is new. Add children with updated hd.

4
Print the Top View
Create an array sortedKeys by sorting the keys of topViewMap in ascending order. Use a for loop to iterate over sortedKeys and print the corresponding values from topViewMap separated by spaces using console.log.
DSA Javascript
Hint

Sort the keys of topViewMap and print the values in order separated by spaces.