Cerinta completa
Given a pointer to the root of a binary tree, print the top view of the binary tree.
The tree as seen from the top the nodes, is called the top view of the tree.
For example :
1
\
2
\
5
/ \
3 6
\
4
Top View :
Complete the function and print the resulting values on a single line separated by space.
Input Format
You are given a function,
void topView(node * root) {
}
Constraints
Nodes in the tree
Output Format
Print the values on a single line separated by space.
Sample Input
1
\
2
\
5
/ \
3 6
\
4
Sample Output
1 2 5 6
Explanation
1
\
2
\
5
/ \
3 6
\
4
From the top, only nodes are visible.
Limbajul de programare folosit: cpp14
Cod:
void topView(Node * root) {
queue<pair<int,Node*>> q; q.push(make_pair(0,root));
map<int,Node*> ans;
for(auto i=q.front();!q.empty();q.pop(),i=q.front()){
if(!i.second) continue;
ans.insert(i);
q.push(make_pair(i.first+1,i.second->right));
q.push(make_pair(i.first-1,i.second->left));
}
for(auto i:ans) cout<<i.second->data<<" ";
}
Scor obtinut: 1.0
Submission ID: 464652849
Link challenge: https://www.hackerrank.com/challenges/tree-top-view/problem
