算法思路
这道题主要考察BFS,我们只需要按照BFS的模板写就可以,只不过在奇数层从左到右输出,偶数层从右至左输出,我们可以用个flag标识奇偶层。
代码实现
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<int> temp; //保留每一层结点的数组
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
if(!pRoot) return res;
queue<TreeNode *>q;
q.push(pRoot);
int flag = false; //标识奇偶层的flag标识
while(!q.empty())
{
int s = q.size();
for(int i =0;i<s;++i)
{
TreeNode *tmp = q.front();
q.pop();
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
if(!flag) temp.push_back(tmp->val);
else temp.insert(temp.begin(),tmp->val); //头插法
}
flag = !flag; //每遍历完一层要切换flag标识
res.push_back(temp);
temp.clear(); //清空该层的数组,下一层的时候这个数组还是空的
}
return res;
}
};