-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path116. TopViewOFBT.cpp
45 lines (39 loc) · 1.02 KB
/
116. TopViewOFBT.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>
/************************************************************
Following is the TreeNode class structure:
template <typename T>
class TreeNode {
public:
T val;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T val) {
this->val = val;
left = NULL;
right = NULL;
}
};
************************************************************/
vector<int> getTopView(TreeNode<int> *root) {
if(root==NULL)return {};
map<int, int> mp;
queue<pair<TreeNode<int> *, int>> q;
q.push({root, 0});
vector<int> ans;
while(!q.empty()){
TreeNode<int> * node = q.front().first;
int v = q.front().second;
q.pop();
if(mp.find(v) == mp.end())mp[v] = node->val;
if(node->left){
q.push({node->left, v-1});
}
if(node->right){
q.push({node->right, v+1});
}
}
for(auto it: mp){
ans.push_back(it.second);
}
return ans;
}