Given a binary tree. The task is to find the top view of the binary tree. The top view of a binary tree is the set of nodes visible when the tree is viewed from the top.
Note:
Return the nodes from the leftmost node to the rightmost node.
If two nodes are at the same position (horizontal distance) and are outside the shadow of the tree, consider the leftmost node only.
Examples:
Example 1: The Green colored nodes represents the top view in the below Binary tree.
Example 2: The Green colored nodes represents the top view in the below Binary tree.
The idea is to use a Depth-First Search (DFS) approach to find the top view of a binary tree. We keep track of horizontal distance from root node. Start from the root node with a distance of 0. When we move to left child we subtract 1 and add 1 when we move to right child to distance of the current node. We use a HashMapto store the top most node that appears at a given horizontal distance. As we traverse the tree, we check if there is any node at current distance in hashmap. If it's the first node encountered at its horizontal distance ,we include it in the top view.
C++
// C++ program to print top// view of binary tree// using dfs#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};// DFS Helper to store top view nodesvoiddfs(Node*node,inthd,intlevel,map<int,pair<int,int>>&topNodes){if(!node)return;// If horizontal distance is encountered for // the first time or if it's at a higher levelif(topNodes.find(hd)==topNodes.end()||topNodes[hd].second>level){topNodes[hd]={node->data,level};}// Recur for left and right subtreesdfs(node->left,hd-1,level+1,topNodes);dfs(node->right,hd+1,level+1,topNodes);}// DFS Approach to find the top view of a binary treevector<int>topView(Node*root){vector<int>result;if(!root)returnresult;// Horizontal distance -> {node's value, level}map<int,pair<int,int>>topNodes;// Start DFS traversaldfs(root,0,0,topNodes);// Collect nodes from the mapfor(autoit:topNodes){result.push_back(it.second.first);}returnresult;}intmain(){// Create a sample binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);vector<int>result=topView(root);for(inti:result){cout<<i<<" ";}return0;}
Java
// Java program to print // top view of binary tree// using dfsimportjava.util.*;classNode{intdata;Nodeleft,right;publicNode(intval){data=val;left=right=null;}}classPair<u,v>{publicufirst;publicvsecond;publicPair(ufirst,vsecond){this.first=first;this.second=second;}publicugetKey(){returnfirst;}publicvgetValue(){returnsecond;}}classGfG{// DFS Helper to store top view nodesstaticvoiddfs(Nodenode,inthd,intlevel,Map<Integer,Pair<Integer,Integer>>topNodes){if(node==null)return;// If horizontal distance is encountered for // the first time or if it's at a higher levelif(!topNodes.containsKey(hd)||topNodes.get(hd).getValue()>level){topNodes.put(hd,newPair<>(node.data,level));}// Recur for left and right subtreesdfs(node.left,hd-1,level+1,topNodes);dfs(node.right,hd+1,level+1,topNodes);}// DFS Approach to find the top view of a binary treestaticArrayList<Integer>topView(Noderoot){ArrayList<Integer>result=newArrayList<>();if(root==null)returnresult;// Horizontal distance -> {node's value, level}Map<Integer,Pair<Integer,Integer>>topNodes=newTreeMap<>();// Start DFS traversaldfs(root,0,0,topNodes);// Collect nodes from the mapfor(Pair<Integer,Integer>value:topNodes.values()){result.add(value.getKey());}returnresult;}publicstaticvoidmain(String[]args){// Create a sample binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);ArrayList<Integer>result=topView(root);for(inti:result){System.out.print(i+" ");}}}
Python
# Python program to print # top view of binary tree# using dfsclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=Nonedefdfs(node,hd,level,top_nodes):ifnotnode:return# If horizontal distance is encountered for # the first time or if it's at a higher levelifhdnotintop_nodesortop_nodes[hd][1]>level:top_nodes[hd]=(node.data,level)# Recur for left and right subtreesdfs(node.left,hd-1,level+1,top_nodes)dfs(node.right,hd+1,level+1,top_nodes)# DFS Approach to find the top view of a binary treedeftopView(root):result=[]ifnotroot:returnresult# Horizontal distance -> (node's value, level)top_nodes={}# Start DFS traversaldfs(root,0,0,top_nodes)# Collect nodes from the mapforkeyinsorted(top_nodes):result.append(top_nodes[key][0])returnresultif__name__=="__main__":# Create a sample binary tree# 1# / \# 2 3# / \ / \# 4 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)result=topView(root)print(" ".join(map(str,result)))
C#
// C# program to print // top view of binary tree// using dfsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGfG{// DFS Helper to store top view nodesstaticvoidDfs(Nodenode,inthd,intlevel,SortedDictionary<int,Tuple<int,int>>topNodes){if(node==null)return;// If horizontal distance is encountered for // the first time or if it's at a higher levelif(!topNodes.ContainsKey(hd)||topNodes[hd].Item2>level){topNodes[hd]=newTuple<int,int>(node.data,level);}// Recur for left and right subtreesDfs(node.left,hd-1,level+1,topNodes);Dfs(node.right,hd+1,level+1,topNodes);}// DFS Approach to find the top view of a binary treestaticList<int>topView(Noderoot){varresult=newList<int>();if(root==null)returnresult;// Horizontal distance -> (node's value, level)vartopNodes=newSortedDictionary<int,Tuple<int,int>>();// Start DFS traversalDfs(root,0,0,topNodes);// Collect nodes from the mapforeach(varvalueintopNodes.Values){result.Add(value.Item1);}returnresult;}staticvoidMain(string[]args){// Create a sample binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);List<int>result=topView(root);Console.WriteLine(string.Join(" ",result));}}
JavaScript
// JavaScript program to print // top view of binary tree// using dfsclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functiondfs(node,hd,level,topNodes){if(!node)return;// If horizontal distance is encountered for // the first time or if it's at a higher levelif(!(hdintopNodes)||topNodes[hd][1]>level){topNodes[hd]=[node.data,level];}// Recur for left and right subtreesdfs(node.left,hd-1,level+1,topNodes);dfs(node.right,hd+1,level+1,topNodes);}// DFS Approach to find the top view of a binary treefunctiontopView(root){letresult=[];if(!root)returnresult;// Horizontal distance -> [node's value, level]lettopNodes={};// Start DFS traversaldfs(root,0,0,topNodes);// Collect nodes from the mapfor(letkeyofObject.keys(topNodes).sort((a,b)=>a-b)){result.push(topNodes[key][0]);}returnresult;}// driver code// Create a sample binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);constresult=topView(root);console.log(result.join(" "));
Output
4 2 1 3 7
Using BFS - O(n * log n) Time and O(n) Space
The idea is similar to Vertical Order Traversal. Like vertical Order Traversal, we need to put nodes of the same horizontal distance together. We just do alevel order traversal(bfs) instead of dfs so that the topmost node at a horizontal distance is visited before any other node of the same horizontal distance below it.
C++
// C++ program to print top// view of binary tree// using bfs#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};// Function to return the top view of a binary treevector<int>topView(Node*root){vector<int>result;if(!root)returnresult;// Map to store the first node at each // horizontal distance (hd)map<int,int>topNodes;// Queue to store nodes along with their// horizontal distancequeue<pair<Node*,int>>q;// Start BFS with the root node at // horizontal distance 0q.push({root,0});while(!q.empty()){autonodeHd=q.front();// Current nodeNode*node=nodeHd.first;// Current horizontal distanceinthd=nodeHd.second;q.pop();// If this horizontal distance is seen for the first// time, store the nodeif(topNodes.find(hd)==topNodes.end()){topNodes[hd]=node->data;}// Add left child to the queue with horizontal// distance - 1if(node->left){q.push({node->left,hd-1});}// Add right child to the queue with // horizontal distance + 1if(node->right){q.push({node->right,hd+1});}}// Extract the nodes from the map in sorted order // of their horizontal distancesfor(autoit:topNodes){result.push_back(it.second);}returnresult;}intmain(){// Create a sample binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);vector<int>result=topView(root);for(inti:result){cout<<i<<" ";}return0;}
Java
// Java program to print top// view of binary tree// using bfsimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}// Function to return the top view of a binary treeclassGfG{staticArrayList<Integer>topView(Noderoot){ArrayList<Integer>result=newArrayList<>();if(root==null)returnresult;// Map to store the first node at each // horizontal distance (hd)Map<Integer,Integer>topNodes=newTreeMap<>();// Queue to store nodes along with their horizontal distanceQueue<Map.Entry<Node,Integer>>q=newLinkedList<>();// Start BFS with the root node at horizontal distance 0q.add(newAbstractMap.SimpleEntry<>(root,0));while(!q.isEmpty()){Map.Entry<Node,Integer>nodeHd=q.poll();// Current nodeNodenode=nodeHd.getKey();// Current horizontal distanceinthd=nodeHd.getValue();// If this horizontal distance is seen for// the first time, store the nodeif(!topNodes.containsKey(hd)){topNodes.put(hd,node.data);}// Add left child to the queue with horizontal distance - 1if(node.left!=null){q.add(newAbstractMap.SimpleEntry<>(node.left,hd-1));}// Add right child to the queue with horizontal// distance + 1if(node.right!=null){q.add(newAbstractMap.SimpleEntry<>(node.right,hd+1));}}// Extract the nodes from the map in sorted order// of their horizontal distancesfor(Integervalue:topNodes.values()){result.add(value);}returnresult;}publicstaticvoidmain(String[]args){// Create a sample binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);ArrayList<Integer>result=topView(root);for(inti:result){System.out.print(i+" ");}}}
Python
# Python program to print top# view of binary tree# using bfsfromcollectionsimportdequeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function to return the top view of# a binary treedeftopView(root):result=[]ifnotroot:returnresult# Map to store the first node at each# horizontal distance (hd)topNodes={}# Queue to store nodes along with their horizontal distanceq=deque([(root,0)])# Start BFS with the root node at horizontal distance 0whileq:node,hd=q.popleft()# If this horizontal distance is seen for the # first time, store the nodeifhdnotintopNodes:topNodes[hd]=node.data# Add left child to the queue with horizontal# distance - 1ifnode.left:q.append((node.left,hd-1))# Add right child to the queue with horizontal# distance + 1ifnode.right:q.append((node.right,hd+1))# Extract the nodes from the map in sorted order of# their horizontal distancesforkeyinsorted(topNodes.keys()):result.append(topNodes[key])returnresultif__name__=="__main__":# Create a sample binary tree# 1# / \# 2 3# / \ / \# 4 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)result=topView(root)print(" ".join(map(str,result)))
C#
// C# program to print top// view of binary tree// using bfsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGfG{// Function to return the top view of a binary treestaticList<int>topView(Noderoot){List<int>result=newList<int>();if(root==null)returnresult;// Map to store the first node at each horizontal// distance (hd)SortedDictionary<int,int>topNodes=newSortedDictionary<int,int>();// Queue to store nodes along with their horizontal// distanceQueue<KeyValuePair<Node,int>>q=newQueue<KeyValuePair<Node,int>>();// Start BFS with the root node at horizontal// distance 0q.Enqueue(newKeyValuePair<Node,int>(root,0));while(q.Count>0){varnodeHd=q.Dequeue();// Current nodeNodenode=nodeHd.Key;// Current horizontal distanceinthd=nodeHd.Value;// If this horizontal distance is seen for the// first time, store the nodeif(!topNodes.ContainsKey(hd)){topNodes[hd]=node.data;}// Add left child to the queue with horizontal// distance - 1if(node.left!=null){q.Enqueue(newKeyValuePair<Node,int>(node.left,hd-1));}// Add right child to the queue with horizontal// distance + 1if(node.right!=null){q.Enqueue(newKeyValuePair<Node,int>(node.right,hd+1));}}// Extract the nodes from the map in sorted order of// their horizontal distancesforeach(varitemintopNodes){result.Add(item.Value);}returnresult;}staticvoidMain(string[]args){// Create a sample binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);List<int>result=topView(root);foreach(intvalinresult){Console.Write(val+" ");}}}
JavaScript
// JavaScript program to print top// view of binary tree// using bfsclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Function to return the top view of// a binary treefunctiontopView(root){letresult=[];if(!root)returnresult;// Map to store the first node at each // horizontal distance (hd)lettopNodes=newMap();// Queue to store nodes along with their// horizontal distanceletq=[];q.push([root,0]);// Start BFS with the root node at horizontal distance 0while(q.length>0){let[node,hd]=q.shift();// If this horizontal distance is seen for the// first time, store the nodeif(!topNodes.has(hd)){topNodes.set(hd,node.data);}// Add left child to the queue with horizontal// distance - 1if(node.left){q.push([node.left,hd-1]);}// Add right child to the queue with horizontal// distance + 1if(node.right){q.push([node.right,hd+1]);}}// Extract the nodes from the map in sorted order of their// horizontal distancesfor(let[key,value]of[...topNodes.entries()].sort((a,b)=>a[0]-b[0])){result.push(value);}returnresult;}//driver code// Create a sample binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);letresult=topView(root);console.log(result.join(" "));
Output
4 2 1 3 7
Optimized Approach Using BFS - O(n) Time and O(n) Space
A queue is used to perform level-order traversal, storing each node along with its corresponding horizontal distance from the root. hashmap keeps track of the topmost node at every horizontal distance. During traversal, if a node at a given horizontal distance is encountered for the first time, it is added to the map.
Additionally, the minimum horizontal distance (mn) is updated to organize the result. After completing the traversal, the map's values are transferred to a result array, adjusting indices based on mn to ensure the nodes are arranged correctly from leftmost to rightmost in the top view. BFS approach ensures that nodes closer to the root and encountered first are prioritized in the top view.
C++
// C++ program to print top view of binary tree// optimally using bfs#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};// Function to return a list of nodes visible// from the top view from left to right in Binary Tree.vector<int>topView(Node*root){// base caseif(root==nullptr){return{};}Node*temp=nullptr;// creating empty queue for level order traversal.queue<pair<Node*,int>>q;// creating a map to store nodes at a// particular horizontal distance.unordered_map<int,int>mp;intmn=INT_MAX;q.push({root,0});while(!q.empty()){temp=q.front().first;intd=q.front().second;mn=min(mn,d);q.pop();// storing temp->data in map.if(mp.find(d)==mp.end()){mp[d]=temp->data;}// if left child of temp exists, pushing it in// the queue with the horizontal distance.if(temp->left){q.push({temp->left,d-1});}// if right child of temp exists, pushing it in// the queue with the horizontal distance.if(temp->right){q.push({temp->right,d+1});}}vector<int>ans(mp.size());// traversing the map and storing the nodes in list// at every horizontal distance.for(autoit=mp.begin();it!=mp.end();it++){ans[it->first-mn]=(it->second);}returnans;}intmain(){// Create a sample binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);vector<int>result=topView(root);for(inti:result){cout<<i<<" ";}return0;}
Java
// Java program to print top view of binary tree// optimally using bfsimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classGfG{// Function to return a list of nodes visible from the// top view from left to right in Binary Tree.staticArrayList<Integer>topView(Noderoot){// Base case: if the tree is empty, return an empty// listif(root==null){returnnewArrayList<>();}// Queue to perform level order traversal.// Each element in the queue is a pair of (Node,// horizontal distance)Queue<Pair>queue=newLinkedList<>();queue.add(newPair(root,0));// HashMap to store the first node at each// horizontal distanceHashMap<Integer,Integer>map=newHashMap<>();// Variables to track the minimum and maximum// horizontal distancesintminHD=0;intmaxHD=0;while(!queue.isEmpty()){Paircurrent=queue.poll();NodecurrentNode=current.node;inthd=current.dist;// Update min and max horizontal distancesif(hd<minHD){minHD=hd;}if(hd>maxHD){maxHD=hd;}// If a horizontal distance is encountered for// the first time, add it to the mapif(!map.containsKey(hd)){map.put(hd,currentNode.data);}// Enqueue the left child with horizontal// distance hd - 1if(currentNode.left!=null){queue.add(newPair(currentNode.left,hd-1));}// Enqueue the right child with horizontal// distance hd + 1if(currentNode.right!=null){queue.add(newPair(currentNode.right,hd+1));}}// Prepare the result list by traversing from minHD// to maxHDArrayList<Integer>topViewList=newArrayList<>();for(inthd=minHD;hd<=maxHD;hd++){if(map.containsKey(hd)){topViewList.add(map.get(hd));}}returntopViewList;}// Helper class to store a node along with its// horizontal distancestaticclassPair{Nodenode;intdist;Pair(Nodenode,intdist){this.node=node;this.dist=dist;}}publicstaticvoidmain(String[]args){// Create a sample binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);ArrayList<Integer>result=topView(root);for(inti:result){System.out.print(i+" ");}}}
Python
# Python program to print top view of binary tree# optimally using bfsfromqueueimportQueueclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to return a list of nodes visible# from the top view from left to right in Binary Tree.deftopView(root):# base caseifnotroot:return[]temp=None# creating empty queue for level order traversal.q=Queue()# creating a dictionary to store nodes at a# particular horizontal distance.mp={}mn=float('inf')q.put((root,0))whilenotq.empty():temp,d=q.get()mn=min(mn,d)# storing temp.data in dictionary.ifdnotinmp:mp[d]=temp.data# if left child of temp exists, pushing it in# the queue with the horizontal distance.iftemp.left:q.put((temp.left,d-1))# if right child of temp exists, pushing it in# the queue with the horizontal distance.iftemp.right:q.put((temp.right,d+1))# Initialize result array with size equal to dictionary sizeans=[0]*len(mp)# Fill result array based on horizontal distancesford,valueinmp.items():ans[d-mn]=valuereturnansif__name__=="__main__":# Create a sample binary tree# 1# / \# 2 3# / \ / \# 4 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)result=topView(root)print(" ".join(map(str,result)))
C#
// C# program to print top view of binary tree// optimally using bfsusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGfG{// Function to return a list of nodes visible// from the top view from left to right in Binary Tree.publicstaticList<int>TopView(Noderoot){// base caseif(root==null)returnnewList<int>();Nodetemp=null;// creating empty queue for level order traversal.Queue<(Node,int)>q=newQueue<(Node,int)>();// creating a dictionary to store nodes at a// particular horizontal distance.Dictionary<int,int>mp=newDictionary<int,int>();intmn=int.MaxValue;q.Enqueue((root,0));while(q.Count>0){varfront=q.Dequeue();temp=front.Item1;intd=front.Item2;mn=Math.Min(mn,d);// storing temp.data in dictionary.if(!mp.ContainsKey(d)){mp[d]=temp.data;}// if left child of temp exists, pushing it in// the queue with the horizontal distance.if(temp.left!=null){q.Enqueue((temp.left,d-1));}// if right child of temp exists, pushing it in// the queue with the horizontal distance.if(temp.right!=null){q.Enqueue((temp.right,d+1));}}// Initialize result array with size equal to// dictionary sizeList<int>ans=newList<int>(newint[mp.Count]);// Fill result array based on horizontal distancesforeach(varentryinmp){ans[entry.Key-mn]=entry.Value;}returnans;}staticvoidMain(string[]args){// Create a sample binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);List<int>result=TopView(root);Console.WriteLine(string.Join(" ",result));}}
JavaScript
// JavaScript program to print top view of binary tree// optimally using bfsclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}functiontopView(root){// Base caseif(root===null){return[];}// Queue for level order traversalletqueue=[];// Map to store nodes at a particular horizontal// distanceletmap=newMap();// Track the minimum horizontal distanceletminDistance=Number.MAX_VALUE;// Start with the root at horizontal distance 0queue.push([root,0]);while(queue.length>0){let[temp,d]=queue.shift();// Update the minimum horizontal distanceminDistance=Math.min(minDistance,d);// If the horizontal distance is not yet in the map,// add itif(!map.has(d)){map.set(d,temp.data);}// Add left child with horizontal distance d - 1if(temp.left){queue.push([temp.left,d-1]);}// Add right child with horizontal distance d + 1if(temp.right){queue.push([temp.right,d+1]);}}// Create the result array with size equal to map sizeletans=newArray(map.size);// Populate the result array using the mapfor(let[key,value]ofmap){ans[key-minDistance]=value;}returnans;}// Driver code// Create a sample binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);letresult=topView(root);console.log(result.join(" "));
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.