题目:
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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
使用 BFS,奇偶层轮流走,一层左到右,一层右到左。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > ans;
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
if(root == NULL) return ans;
vector<TreeNode*> q1, q2;
q1.push_back(root);
int depth = 0;
while(!q1.empty() || !q2.empty())
{
ans.push_back(vector<int>(0));
for(int i = q1.size() - 1; i >= 0; i --)
{
ans[depth].push_back(q1[i]->val);
if(q1[i]->left != NULL) q2.push_back(q1[i]->left);
if(q1[i]->right != NULL) q2.push_back(q1[i]->right);
}
depth ++;
q1.clear();
if(q2.empty()) continue;
ans.push_back(vector<int>(0));
for(int i = q2.size() - 1; i >= 0; i --)
{
ans[depth].push_back(q2[i]->val);
if(q2[i]->right != NULL) q1.push_back(q2[i]->right);
if(q2[i]->left != NULL) q1.push_back(q2[i]->left);
}
q2.clear();
depth ++;
}
return ans;
}
};