题目描述
思路分析
二叉树+bfs
分行层次遍历对奇偶分情况讨论即可。引入
z
i
g
z
a
g
zigzag
zigzag变量,每行
z
i
g
z
a
g
zigzag
zigzag对取个反。
代码实现
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
vector<int> path;
bool zigzag=false;
while(q.size()){
auto t=q.front();
q.pop();
if(!t){
if(!path.size()) break;
if(zigzag) reverse(path.begin(),path.end());
res.push_back(path);
path.clear();
q.push(nullptr);
zigzag=!zigzag;
continue;
}
path.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
return res;
}
};