/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /*二叉树层次遍历de算法思想: 利用一个队列(用来保存下一步的处理顺序),根结点入队,如果队首结点有左孩子则入队 如果队首结点由右孩子则也入队,依次入队后利用for循环导入out0中,外面的while 实现多层依次导入out。 PS:因为要分层输出,所以要注意while循环每次要将同一层中的结点同时入队 */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { queue<TreeNode*> t; //创建一个队列 vector<vector<int>> out; if(!root) return out; TreeNode* tmp; t.push(root); //先把头结点入队列 while(!t.empty()) //如果队列不空的话 { vector<int> out0; int width=t.size(); for(int i=0;i<width;i++){ tmp=t.front(); if(tmp->left) t.push(tmp->left); if(tmp->right) t.push(tmp->right); out0.push_back(tmp->val); t.pop(); } out.push_back(out0); //把每一层放入二维对应层中 } return out; } };