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
原文:https://www.cnblogs.com/zzw1024/p/11681727.html