题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
题解:
使用BFS,按层打印即可
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 };