题目
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
Z字形遍历。
实际就是第1层从左向右遍历,第二层从右向左遍历……
依然可以用bfs解决,
每扫完一层后将队列反转,
如果是奇数层,左节点先入队列;
如果是偶数层,右节点先入队列。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
struct pt //bfs用点
{
TreeNode *node; //探测到的位置
int level; //相应的层
pt(TreeNode *n=NULL,int l=0):node(n),level(l){}
};
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int>> ret;
deque<pt> queue(1,pt(root)); //队列
while(!queue.empty()) //bfs
{
if(queue.front().node!=NULL)
{
if(queue.front().level>=ret.size()) //每换一层时将队列翻转
{
ret.push_back(vector<int>());
reverse(queue.begin(),queue.end());
continue;
}
ret[queue.front().level].push_back(queue.front().node->val);
if(ret.size()%2==1) //正向入队
{
queue.push_back(pt(queue.front().node->left,queue.front().level+1));
queue.push_back(pt(queue.front().node->right,queue.front().level+1));
}
else //反向入队
{
queue.push_back(pt(queue.front().node->right,queue.front().level+1));
queue.push_back(pt(queue.front().node->left,queue.front().level+1));
}
}
queue.pop_front();
}
return ret;
}
};