fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct TreeNode{
  4. int val;
  5. TreeNode* left;
  6. TreeNode* right;
  7. TreeNode(int val):left(nullptr),right(nullptr),val(val){};
  8. };
  9. vector<vector<int>>spiral(TreeNode* root){
  10. vector<vector<int>>ans;
  11. if(root == nullptr)return ans;
  12.  
  13. queue<TreeNode*>q;
  14. q.push(root);
  15. bool trn = false;
  16. while(!q.empty()){
  17. int sz = q.size();
  18. vector<int>lvl;
  19. for(int i = 0;i<sz;i++){
  20. auto u = q.front();
  21. q.pop();
  22. lvl.push_back(u->val);
  23. if(u->left){
  24. q.push(u->left);
  25. }
  26.  
  27. if(u->right){
  28. q.push(u->right);
  29. }
  30. }
  31. if(trn)reverse(lvl.begin(),lvl.end());
  32. ans.push_back(lvl);
  33. trn = !trn;
  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<vector<int>>ans = spiral(root);
  64. for(auto &x : ans){
  65. for(auto &y:x){
  66. cout<<y<<" ";
  67. }
  68. cout<<endl;
  69. }
  70. return 0;
  71. }
Success #stdin #stdout 0s 5320KB
stdin
1 2 3 -1 4 8 5
stdout
1 
3 2 
4 8 5