Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Solution:
BFS, 树的层序遍历就是用的queue,因为BFS有一个显著的概念就是分层,必须遍历完本层之后,再去遍历下一层。如果不要求区分每一层的话,那么实际上一个队列就能完成。就像经典的树的层序遍历一样,上层的元素肯定首先放入到队列中,下层的元素一定都在上一层元素遍历完之后,才会被遍历。
当要考虑层数是需要用到两个队列。首先将元素放入q1中,然后对q1中的元素出队列,将其左右子树(如果有的话)放入q2中。当q1遍历完毕之后,说明本层已经遍历完毕了,那么就交换q1和q2,继续遍历新的q1(也就是原来的q2),最终,当两个队列都为空(实际上也就是最后交换完毕之后的q1为空)的时候,整个树就都遍历完毕了
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> ret; if(!root)return ret; vector<int> vec; queue<TreeNode*> q1,q2; q1.push(root); while(!q1.empty()){ while(!q1.empty()){ TreeNode *temp=q1.front(); vec.push_back(temp->val); q1.pop(); if(temp->left)q2.push(temp->left); if(temp->right)q2.push(temp->right); } ret.push_back(vec); vec.clear(); swap(q1,q2); //swap不需要头文件 } return ret; } };