题目描述:
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:[
[3],
[20,9],
[15,7]
]
算法:BFS
使用辅助队列,每次遍历下一层时,先读取下一层的元素
/**
* 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>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>>ans;
if(root == NULL)
return ans;
queue<TreeNode* > q;
q.push(root);
while(!q.empty())
{
vector<int>temp;
int currentSize = q.size();
for(int i=0; i<currentSize; i++)
{
TreeNode* point = q.front();
q.pop();
temp.push_back(point->val);
if(point->left)
q.push(point->left);
if(point->right)
q.push(point->right);
}
ans.push_back(temp);
}
for(int i=0; i<ans.size(); i++)
{
if(i % 2 == 1)
reverse(ans[i].begin(), ans[i].end());
}
return ans;
}
};