题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
广度优先搜索
class Solution { public: vector<vector<int> > levelOrder(TreeNode* root) { // write code here if(!root) return {}; vector<vector<int> > res; queue<TreeNode*> q; q.push(root); vector<int> line; while(!q.empty()){ line.clear(); int sz = q.size(); for(int i=0; i<sz; ++i){ TreeNode* cur = q.front(); q.pop(); line.push_back(cur->val); if(cur->left) q.push(cur->left); if(cur->right) q.push(cur->right); } res.push_back(line); } return res; } };