fork(1) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. class tree
  4. {
  5. public:
  6. int data;
  7. tree*left;
  8. tree*right;
  9. tree(int d)
  10. {
  11. data=d;
  12. left=NULL;
  13. right=NULL;
  14. }
  15. };
  16. tree*build()
  17. {
  18. int d;
  19. cin>>d;
  20. if(d==-1) return NULL;
  21. tree*root=new tree(d);
  22. root->left=build();
  23. root->right=build();
  24. return root;
  25. }
  26. void verticalorderprint(tree*root,int dist,map<int,int>&m)
  27. {
  28. if(root->left==0 && root->right==0)
  29. return;
  30.  
  31. m[dist]=root->data;
  32.  
  33. verticalorderprint(root->left,dist+=-1,m);
  34. verticalorderprint(root->right,dist+=1,m);
  35. }
  36. int main()
  37. {
  38. tree*root=build();
  39. map<int,int> m;
  40. verticalorderprint(root,0,m);
  41. for(auto it=m.begin();it!=m.end();it++) cout<<it->second<<" ";
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0s 15240KB
stdin
1 2 4 -1 -1 5 -1 -1 3 6 -1 -1 7 -1 -1 
stdout
2 3