Wins the offer - 33 binary tree branches are printed upside down

Title Description

Printing the binary tree in layers from top to bottom, from left to right with the output layer node. Each line of output layer.
 
answer:
  Use BFS, you can print by layer
  
 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         while (!q.empty())
14         {
15             queue<TreeNode*>temp;
16             vector<int>v;
17             while (!q.empty())
18             {                
19                 TreeNode* p = q.front();
20                 q.pop();
21                 v.push_back(p->val);
22                 if (p->left != nullptr)temp.push(p->left);
23                 if (p->right != nullptr)temp.push(p->right);
24             }
25             res.push_back(v);
26             q = temp;
27         }
28     }
29 };

 

Guess you like

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