Binary Tree Zigzag Level Order Traversal
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] ]
/**
* 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> > zigzagLevelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > result;
vector<TreeNode*> level;
if(root)
level.push_back(root);
bool flag=false;
while(!level.empty()){
vector<TreeNode*> next;
vector<int> r;
for(int i=0;i<level.size();++i){
r.push_back(level[i]->val);
if(level[i]->left)
next.push_back(level[i]->left);
if(level[i]->right)
next.push_back(level[i]->right);
}
if(flag)
reverse(r.begin(),r.end());
flag=!flag;
result.push_back(r);
level=next;
}
return result;
}
};