Given the root of a binary tree, find the top view of the tree. The top view of a binary tree represents the set of nodes visible when the tree is viewed from above.
Each node in the tree has a horizontal distance (HD) from the root, which helps determine its position when viewed from the top:
The root node has an HD of 0.
The left child of a node has an HD equal to parent’s HD - 1.
The right child of a node has an HD equal to parent’s HD + 1.
Note:
The result should contain the nodes visible from leftmost to rightmost and if two nodes have the same horizontal distance, only the uppermost (first encountered) node should be considered in the top view.
Examples:
Input:
Output: [2, 1, 3] Explanation: The Greencolored nodes represents the top view in the below Binary tree.
Input:
Output: [40, 20, 10, 30, 100] Explanation:The Greencolored nodes represents the top view in the below Binary tree.
[Approach 1] Using DFS - O(n * log n) Time and O(n) Space
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 HashMap to 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++
#include<iostream>#include<vector>#include<map>usingnamespacestd;// Node StructureclassNode{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);}// Finding 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// 10// / \ // 20 30// / \ / \ // 40 60 90 100Node*root=newNode(10);root->left=newNode(20);root->right=newNode(30);root->left->left=newNode(40);root->left->right=newNode(60);root->right->left=newNode(90);root->right->right=newNode(100);vector<int>result=topView(root);for(inti:result){cout<<i<<" ";}return0;}
Java
importjava.util.ArrayList;importjava.util.Map;importjava.util.TreeMap;// Node StructureclassNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=right=null;}}classGFG{// DFS Helper to store top view nodesstaticvoiddfs(Nodenode,inthd,intlevel,Map<Integer,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.get(hd)[1]>level){topNodes.put(hd,newint[]{node.data,level});}// Recur for left and right subtreesdfs(node.left,hd-1,level+1,topNodes);dfs(node.right,hd+1,level+1,topNodes);}// Finding the top view of a binary treestaticArrayList<Integer>topView(Noderoot){ArrayList<Integer>result=newArrayList<>();if(root==null)returnresult;// Horizontal distance -> {node's value, level}TreeMap<Integer,int[]>topNodes=newTreeMap<>();// Start DFS traversaldfs(root,0,0,topNodes);// Collect nodes from the mapfor(Map.Entry<Integer,int[]>entry:topNodes.entrySet()){result.add(entry.getValue()[0]);}returnresult;}publicstaticvoidmain(String[]args){// Create a sample binary tree// 10// / \// 20 30// / \ / \// 40 60 90 100Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);root.right.left=newNode(90);root.right.right=newNode(100);ArrayList<Integer>result=topView(root);for(inti:result){System.out.print(i+" ");}}}
Python
# Node StructureclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# DFS Helper to store top view nodesdefdfs(node,hd,level,topNodes):ifnodeisNone:return# If horizontal distance is encountered for # the first time or if it's at a higher levelifhdnotintopNodesortopNodes[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)# Finding the top view of a binary treedeftopView(root):result=[]ifrootisNone:returnresult# Horizontal distance -> (node's value, level)topNodes=dict()# Start DFS traversaldfs(root,0,0,topNodes)# Collect nodes from the map sorted by horizontal distanceforhdinsorted(topNodes.keys()):result.append(topNodes[hd][0])returnresultif__name__=="__main__":# Create a sample binary tree# 10# / \# 20 30# / \ / \# 40 60 90 100root=Node(10)root.left=Node(20)root.right=Node(30)root.left.left=Node(40)root.left.right=Node(60)root.right.left=Node(90)root.right.right=Node(100)result=topView(root)print(" ".join(map(str,result)))
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGFG{// Finding the top view of a binary treestaticvoiddfs(Nodenode,inthd,intlevel,SortedDictionary<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][1]>level){topNodes[hd]=newint[]{node.data,level};}// Recur for left and right subtreesdfs(node.left,hd-1,level+1,topNodes);dfs(node.right,hd+1,level+1,topNodes);}// Finding the top view of a binary treestaticList<int>topView(Noderoot){List<int>result=newList<int>();if(root==null)returnresult;// Horizontal distance -> {node's value, level}SortedDictionary<int,int[]>topNodes=newSortedDictionary<int,int[]>();// Start DFS traversaldfs(root,0,0,topNodes);// Collect nodes from the mapforeach(varkvpintopNodes){result.Add(kvp.Value[0]);}returnresult;}staticvoidMain(string[]args){// Create a sample binary tree// 10// / \// 20 30// / \ / \// 40 60 90 100Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);root.right.left=newNode(90);root.right.right=newNode(100);List<int>result=TopView(root);foreach(intiinresult){Console.Write(i+" ");}}}
JavaScript
// Node StructureclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// DFS Helper to store top view nodesfunctiondfs(node,hd,level,topNodes){if(node===null)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);}// Finding the top view of a binary treefunctiontopView(root){constresult=[];if(root===null)returnresult;// Horizontal distance -> [node's value, level]consttopNodes={};// Start DFS traversaldfs(root,0,0,topNodes);// Collect nodes from the map sorted by horizontal distanceconstsortedKeys=Object.keys(topNodes).map(Number).sort((a,b)=>a-b);for(constkeyofsortedKeys){result.push(topNodes[key][0]);}returnresult;}// Driver Code// Create a sample binary tree// 10// / \// 20 30// / \ / \// 40 60 90 100constroot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);root.right.left=newNode(90);root.right.right=newNode(100);constresult=topView(root);console.log(result.join(" "));
Output
40 20 10 30 100
[Approach 2] 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 a level 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++
#include<iostream>#include<vector>#include<queue>#include<map>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};vector<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;q.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// / \ // 20 30// / \ / \ // 40 60 90 100Node*root=newNode(10);root->left=newNode(20);root->right=newNode(30);root->left->left=newNode(40);root->left->right=newNode(60);root->right->left=newNode(90);root->right->right=newNode(100);vector<int>result=topView(root);for(inti:result){cout<<i<<" ";}return0;}
Java
importjava.util.ArrayList;importjava.util.List;importjava.util.Map;importjava.util.Queue;importjava.util.LinkedList;importjava.util.TreeMap;// Node StructureclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGFG{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<Object[]>q=newLinkedList<>();q.add(newObject[]{root,0});while(!q.isEmpty()){Object[]nodeHd=q.poll();// Current nodeNodenode=(Node)nodeHd[0];// Current horizontal distanceinthd=(int)nodeHd[1];// 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(newObject[]{node.left,hd-1});}// Add right child to the queue with // horizontal distance + 1if(node.right!=null){q.add(newObject[]{node.right,hd+1});}}// Extract the nodes from the map in sorted order // of their horizontal distancesfor(Map.Entry<Integer,Integer>entry:topNodes.entrySet()){result.add(entry.getValue());}returnresult;}publicstaticvoidmain(String[]args){// Create a sample binary tree// 10// / \// 20 30// / \ / \// 40 60 90 100Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);root.right.left=newNode(90);root.right.right=newNode(100);List<Integer>result=topView(root);for(inti:result){System.out.print(i+" ");}}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedeftopView(root):result=[]ifrootisNone:returnresult# Map to store the first node at each # horizontal distance (hd)topNodes={}# Queue to store nodes along with their# horizontal distanceq=deque()q.append((root,0))whileq: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 distancesforhdinsorted(topNodes.keys()):result.append(topNodes[hd])returnresultif__name__=="__main__":# Create a sample binary tree# 10# / \# 20 30# / \ / \# 40 60 90 100root=Node(10)root.left=Node(20)root.right=Node(30)root.left.left=Node(40)root.left.right=Node(60)root.right.left=Node(90)root.right.right=Node(100)result=topView(root)print(" ".join(map(str,result)))
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGFG{staticList<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<Tuple<Node,int>>q=newQueue<Tuple<Node,int>>();q.Enqueue(newTuple<Node,int>(root,0));while(q.Count>0){varnodeHd=q.Dequeue();// Current nodeNodenode=nodeHd.Item1;// Current horizontal distanceinthd=nodeHd.Item2;// 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(newTuple<Node,int>(node.left,hd-1));}// Add right child to the queue with // horizontal distance + 1if(node.right!=null){q.Enqueue(newTuple<Node,int>(node.right,hd+1));}}// Extract the nodes from the map in sorted order // of their horizontal distancesforeach(varkvpintopNodes){result.Add(kvp.Value);}returnresult;}staticvoidMain(string[]args){// Create a sample binary tree// 10// / \// 20 30// / \ / \// 40 60 90 100Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);root.right.left=newNode(90);root.right.right=newNode(100);List<int>result=topView(root);foreach(intiinresult){Console.Write(i+" ");}}}
JavaScript
// Node StructureclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functiontopView(root){constresult=[];if(!root)returnresult;// Map to store the first node at each // horizontal distance (hd)consttopNodes={};// Queue to store nodes along with their// horizontal distanceconstq=[];q.push([root,0]);while(q.length){const[node,hd]=q.shift();// If this horizontal distance is seen for the first// time, store the nodeif(!(hdintopNodes)){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 distancesconstsortedKeys=Object.keys(topNodes).map(Number).sort((a,b)=>a-b);for(constkeyofsortedKeys){result.push(topNodes[key]);}returnresult;}// Driver Code// Sample binary tree// 10// / \// 20 30// / \ / \// 40 60 90 100constroot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);root.right.left=newNode(90);root.right.right=newNode(100);constresult=topView(root);console.log(result.join(" "));
Output
40 20 10 30 100
[Optimized Approach] Using BFS - O(n) Time and O(n) Space
The top view of a binary tree can be found using BFS. A queue stores each node with its horizontal distance from the root, while a hashmap keeps track of the first node seen at each distance. During traversal, nodes at new horizontal distances are added to the map, and the minimum distance is tracked. After traversal, the map’s values are transferred to a result array in order from leftmost to rightmost, ensuring that nodes closer to the root appear first in the top view.
C++
#include<iostream>#include<vector>#include<queue>#include<unordered_map>#include<climits>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};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// 10// / \ // 20 30// / \ / \ // 40 60 90 100Node*root=newNode(10);root->left=newNode(20);root->right=newNode(30);root->left->left=newNode(40);root->left->right=newNode(60);root->right->left=newNode(90);root->right->right=newNode(100);vector<int>result=topView(root);for(inti:result){cout<<i<<" ";}return0;}
Java
importjava.util.ArrayList;importjava.util.HashMap;importjava.util.LinkedList;importjava.util.Queue;importjava.util.Map;// Node StructureclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}// Pair class to store node and its horizontal distanceclassNodeHd{Nodenode;inthd;NodeHd(Noden,inth){node=n;hd=h;}}classGFG{staticArrayList<Integer>topView(Noderoot){ArrayList<Integer>ans=newArrayList<>();if(root==null)returnans;// Queue for level order traversal storing node and horizontal distanceQueue<NodeHd>q=newLinkedList<>();q.add(newNodeHd(root,0));// Map to store first node at each horizontal distanceMap<Integer,Integer>mp=newHashMap<>();intminHd=Integer.MAX_VALUE;while(!q.isEmpty()){NodeHdtemp=q.poll();Nodenode=temp.node;inthd=temp.hd;minHd=Math.min(minHd,hd);// store the first node encountered at this horizontal distanceif(!mp.containsKey(hd)){mp.put(hd,node.data);}if(node.left!=null)q.add(newNodeHd(node.left,hd-1));if(node.right!=null)q.add(newNodeHd(node.right,hd+1));}// convert map to list in order from leftmost to rightmostintmaxHd=Integer.MIN_VALUE;for(intkey:mp.keySet()){maxHd=Math.max(maxHd,key);}for(inti=minHd;i<=maxHd;i++){ans.add(mp.get(i));}returnans;}publicstaticvoidmain(String[]args){// Create a sample binary tree// 10// / \// 20 30// / \ / \// 40 60 90 100Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);root.right.left=newNode(90);root.right.right=newNode(100);ArrayList<Integer>result=topView(root);for(inti:result){System.out.print(i+" ");}}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedeftopView(root):# base caseifrootisNone:return[]temp=None# creating empty queue for level order traversal.q=deque()# creating a map to store nodes at a# particular horizontal distance.mp={}mn=float('inf')q.append((root,0))whileq:temp,d=q.popleft()mn=min(mn,d)# storing temp.data in map.ifdnotinmp:mp[d]=temp.data# if left child of temp exists, pushing it in# the queue with the horizontal distance.iftemp.left:q.append((temp.left,d-1))# if right child of temp exists, pushing it in# the queue with the horizontal distance.iftemp.right:q.append((temp.right,d+1))ans=[0]*len(mp)# traversing the map and storing the nodes in list# at every horizontal distance.forkey,valinmp.items():ans[key-mn]=valreturnansif__name__=="__main__":# Create a sample binary tree# 10# / \# 20 30# / \ / \# 40 60 90 100root=Node(10)root.left=Node(20)root.right=Node(30)root.left.left=Node(40)root.left.right=Node(60)root.right.left=Node(90)root.right.right=Node(100)result=topView(root)print(" ".join(map(str,result)))
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGFG{staticList<int>topView(Noderoot){// base caseif(root==null)returnnewList<int>();Nodetemp=null;// creating empty queue for level order traversal.Queue<Tuple<Node,int>>q=newQueue<Tuple<Node,int>>();// creating a map to store nodes at a// particular horizontal distance.Dictionary<int,int>mp=newDictionary<int,int>();intmn=int.MaxValue;q.Enqueue(newTuple<Node,int>(root,0));while(q.Count>0){varnodeHd=q.Dequeue();temp=nodeHd.Item1;intd=nodeHd.Item2;mn=Math.Min(mn,d);// storing temp.data in map.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(newTuple<Node,int>(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(newTuple<Node,int>(temp.right,d+1));}List<int>ans=newList<int>(newint[mp.Count]);// traversing the map and storing the nodes in list// at every horizontal distance.foreach(varkvpinmp){ans[kvp.Key-mn]=kvp.Value;}returnans;}staticvoidMain(){// Create a sample binary tree// 10// / \// 20 30// / \ / \// 40 60 90 100Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);root.right.left=newNode(90);root.right.right=newNode(100);List<int>result=topView(root);Console.WriteLine(string.Join(" ",result));}}
JavaScript
// Node StructureclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functiontopView(root){// base caseif(root===null)return[];lettemp=null;// creating empty queue for level order traversal.constq=[];// creating a map to store nodes at a// particular horizontal distance.constmp={};letmn=Infinity;q.push([root,0]);while(q.length>0){let[temp,d]=q.shift();// destructure Node and hd correctlymn=Math.min(mn,d);// storing temp.data in map.if(!(dinmp)){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]);}}constans=newArray(Object.keys(mp).length);// traversing the map and storing the nodes in list// at every horizontal distance.for(constkeyinmp){ans[key-mn]=mp[key];}returnans;}// Driver Code// Create a sample binary tree// 10// / \// 20 30// / \ / \// 40 60 90 100constroot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);root.right.left=newNode(90);root.right.right=newNode(100);constresult=topView(root);console.log(result.join(" "));