Skip to content

Commit d5d2ccc

Browse files
authored
Create main.cpp
1 parent 3af6f20 commit d5d2ccc

File tree

1 file changed

+44
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/18 - Top View of Binary Tree

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution
2+
{
3+
public:
4+
//Function to return a list of nodes visible from the top view
5+
//from left to right in Binary Tree.
6+
vector<int> topView(Node *root)
7+
{
8+
vector<int> ans;
9+
if(root == NULL) return ans;
10+
11+
map<int, int> topNode;
12+
queue<pair<Node*, int>> q;
13+
14+
q.push({root, 0});
15+
16+
while(!q.empty()){
17+
pair<Node*, int> temp = q.front();
18+
q.pop();
19+
20+
Node* frontNode = temp.first;
21+
int hd = temp.second;
22+
23+
if(topNode.find(hd) == topNode.end()){
24+
topNode[hd] = frontNode -> data;
25+
}
26+
27+
if(frontNode -> left){
28+
q.push({frontNode -> left, hd -1});
29+
}
30+
31+
if(frontNode -> right){
32+
q.push({frontNode -> right, hd + 1});
33+
}
34+
35+
}
36+
for(auto i : topNode){
37+
ans.push_back(i.second);
38+
}
39+
40+
41+
return ans;
42+
}
43+
44+
};

0 commit comments

Comments
 (0)