fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct TreeNode{
  4. int val;
  5. TreeNode* right;
  6. TreeNode* left;
  7. TreeNode(int val):left(nullptr),right(nullptr),val(val){};
  8. };
  9.  
  10. vector<int>top(TreeNode* root){
  11. vector<int>ans;
  12. if(root == nullptr)return ans;
  13. map<int,int>mp;
  14. queue<pair<TreeNode*,int>>q;
  15. q.push({root,0});
  16.  
  17. while(!q.empty()){
  18. auto [u,v]= q.front();
  19. q.pop();
  20.  
  21. mp[v]=u->val;
  22.  
  23. if(u->left){
  24. q.push({u->left,v-1});
  25. }
  26.  
  27. if(u->right){
  28. q.push({u->right,v+1});
  29. }
  30. }
  31.  
  32. for(auto [v,val]:mp){
  33. ans.push_back(val);
  34. }
  35. return ans;
  36. }
  37. TreeNode* buildTree(){
  38. int x;cin>>x;
  39. if(x==-1)return nullptr;
  40. TreeNode* root = new TreeNode(x);
  41.  
  42. queue<TreeNode*>q;
  43. q.push(root);
  44.  
  45. while(!q.empty()){
  46. auto u = q.front();
  47. q.pop();
  48.  
  49. if(cin>>x && x!=-1){
  50. u->left = new TreeNode(x);
  51. q.push(u->left);
  52. }
  53.  
  54. if(cin>>x && x!=-1){
  55. u->right = new TreeNode(x);
  56. q.push(u->right);
  57. }
  58. }
  59. return root;
  60. }
  61. int main() {
  62. TreeNode* root = buildTree();
  63. vector<int>ans = top(root);
  64.  
  65. for(auto x : ans){
  66.  
  67. cout<<x<<endl;
  68. }
  69. return 0;
  70. }
Success #stdin #stdout 0s 5316KB
stdin
20 8 22 5 3 -1 25 -1 -1 10 14
stdout
5
10
3
14
25