File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
17 - Binary Tree Data Structure Problems/18 - Top View of Binary Tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments