对于这道题,是在层次遍历的基础上做了简单的变形。
1.可以在每次遍历一层的时候,将其存入vector中,根据奇数还是偶数对其进行翻转,再存入答案的二维vector中。
2.可以用双端队列,如果奇数层,存队尾,取队首。反之存队首,取队尾。这是我第一次想到以及使用双端队列。有所收获。

翻转vector方式:
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
int flag=1;
queue<TreeNode*> q;
queue<int> d;
int n=0;
vector<vector<int>> ans;
vector<int> t;
if(root==nullptr) return ans;
q.push(root);
d.push(0);
while(!q.empty())
{
if(d.front()>n)
{
flag*=(-1);
if(flag==1) reverse(t.begin(),t.end());
ans.push_back(t);
t.clear();
n++;
}
t.push_back(q.front()->val);
if(q.front()->left)
{
q.push(q.front()->left);
d.push(d.front()+1);
}
if(q.front()->right)
{
q.push(q.front()->right);
d.push(d.front()+1);
}
q.pop(); d.pop();
}
flag*=(-1);
if(flag==1) reverse(t.begin(),t.end());
ans.push_back(t);
return ans;
}
};
双端队列(deque):
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
int flag=1;
deque<TreeNode*> q;
queue<int> d;
int n=0;
vector<vector<int>> ans;
vector<int> t;
if(root==nullptr) return ans;
q.push_back(root);
d.push(0);
while(!q.empty())
{
if(d.front()>n)
{
flag*=(-1);
ans.push_back(t);
t.clear();
n++;
}
if(flag==1)
{
t.push_back(q.front()->val);
if(q.front()->left)
{
q.push_back(q.front()->left);
d.push(d.front()+1);
}
if(q.front()->right)
{
q.push_back(q.front()->right);
d.push(d.front()+1);
}
q.pop_front(); d.pop();
}
else
{
t.push_back(q.back()->val);
if(q.back()->right)
{
q.push_front(q.back()->right);
d.push(d.front()+1);
}
if(q.back()->left)
{
q.push_front(q.back()->left);
d.push(d.front()+1);
}
q.pop_back(); d.pop();
}
}
ans.push_back(t);
return ans;
}
};

274

被折叠的 条评论
为什么被折叠?



