class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int>>ans;
queue<TreeNode*>cur,nex;
if(!root)return ans;
cur.push(root);
int level=1;
while(!cur.empty())
{
vector<int>temp;
while(!cur.empty())
{
TreeNode*top=cur.front();
cur.pop();
temp.push_back(top->val);
if(top->left)nex.push(top->left);
if(top->right)nex.push(top->right);
}
swap(cur,nex);
if(level%2==0)reverse(temp.begin(),temp.end());
level++;
ans.push_back(temp);
}
return ans;
}
};
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int>>ans;
queue<TreeNode*>q;
int level=1;
if(!root)return ans;
q.push(root);
while(!q.empty())
{
vector<int>temp;
int size=q.size();
while(size--)
{
TreeNode*top=q.front();
q.pop();
temp.push_back(top->val);
if(top->left)q.push(top->left);
if(top->right)q.push(top->right);
}
if(level%2==0)reverse(temp.begin(),temp.end());
level++;
ans.push_back(temp);
}
return ans;
}
};
网友评论