剑指 Offer 32 - I. 从上到下打印二叉树
class Solution { public: vector<int> levelOrder(TreeNode* root) { if(!root) return {}; queue<TreeNode*> queue; vector<int> res; queue.push(root); while(!queue.empty()){ TreeNode* cur=queue.front(); queue.pop(); res.push_back(cur->val); if(cur->left){ queue.push(cur->left); } if(cur->right){ queue.push(cur->right); } } return res; } };
剑指 Offer 32 - II. 从上到下打印二叉树 II
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { if(!root) return {}; queue<TreeNode*> queue; queue.push(root); vector<vector<int>> res; while(!queue.empty()){ int l=queue.size(); vector<int> tmp; for(int i=0;i<l;i++){ TreeNode* cur=queue.front(); queue.pop(); tmp.push_back(cur->val); if(cur->left){ queue.push(cur->left); } if(cur->right){ queue.push(cur->right); } } res.push_back(tmp); } return res; } };
剑指 Offer 32 - III. 从上到下打印二叉树 III
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { if(!root) return {}; queue<TreeNode*> queue; queue.push(root); vector<vector<int>> res; int flag=0; while(!queue.empty()){ int l=queue.size(); vector<int> tmp; for(int i=0;i<l;i++){ TreeNode* cur=queue.front(); queue.pop(); tmp.push_back(cur->val); if(cur->left){ queue.push(cur->left); } if(cur->right){ queue.push(cur->right); } } if(flag&1==1){ reverse(tmp.begin(),tmp.end()); } res.push_back(tmp); flag++; } return res; } };