标签:struct queue solution 奇数 bin turn null int front
和分行从上到下打印二叉树本质上是一样的,只不过奇数行是从左到右打印,偶数行是从右到左打印.
cpp
/**
* 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>> res;
if(!root)return res;
queue<TreeNode*> q;
q.push(root);
bool zigzag = true;
while(!q.empty()){
vector<int> tmp;
for(int i=q.size();i>0;i--){
auto t = q.front();
q.pop();
tmp.push_back(t->val);
if(t->left)q.push(t->left);
if(t->right)q.push(t->right);
}
zigzag = !zigzag;
if(zigzag)reverse(tmp.begin(),tmp.end());
res.push_back(tmp);
}
return res;
}
};
标签:struct queue solution 奇数 bin turn null int front
原文地址:https://www.cnblogs.com/Rowry/p/14410779.html