To prove safety offer - word of 34 binary tree print

Title Description

Implement according to a zigzag print function binary tree, i.e., left to right, the first print line of the second layer in order to print from right to left, the third line from left to right order of printing, in other rows forth.
 
answer:
  No difference with the previous questions, is stored in the data, the data for odd-numbered rows, the first reverse it, and then we can deposit
  
 1 class Solution {
 2 public:
 3     vector<vector<int> > Print(TreeNode* pRoot) {
 4         vector<vector<int>>res;
 5         BFS(pRoot, res);
 6         return res;
 7     }
 8     void BFS(TreeNode *root, vector<vector<int>>&res)
 9     {
10         if (root == nullptr)return;
11         queue<TreeNode*>q;
12         q.push(root);
13         bool fromLeft = true;
14         while (!q.empty())
15         {
16             queue<TreeNode*>temp;
17             vector<int>v;
18             while (!q.empty())
19             {
20                 TreeNode* p = q.front();
21                 q.pop();
22                 v.push_back(p->val);
23                 if (p->left != nullptr)temp.push(p->left);
24                 if (p->right != nullptr)temp.push(p->right);
25             }
26             if(fromLeft)
27                 res.push_back(v);
28             else
29             {
30                 reverse(v.begin(), v.end());
31                 res.push_back(v);
32             }
33             fromLeft = !fromLeft;
34             q = temp;
35         }
36     }
37 };
38     

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/11681727.html