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]
]
Solution: BFS
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > result;
if(root == NULL)
return result;
vector<TreeNode *> layer;
layer.push_back(root);
bool reverse = false;
while(layer.size() > ) {
vector<int> tmp;
vector<TreeNode *> new_layer;
for(int i = ; i < layer.size(); i ++){
TreeNode * node = layer[i];
if(node->left != NULL)
new_layer.push_back(node->left);
if(node->right != NULL)
new_layer.push_back(node->right);
if(reverse)
tmp.push_back(layer[layer.size() - - i]->val);
else
tmp.push_back(node->val);
}
if(reverse)
reverse = false;
else
reverse = true;
result.push_back(tmp);
layer = new_layer;
}
}