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] ]
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> > zigzagLevelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int>> matrix;
if(root == NULL) return matrix;
vector<int> tmp;
tmp.push_back(root->val);
matrix.push_back(tmp);
vector<TreeNode*> path;
path.push_back(root);
int count = 1;
bool lefttoright = false;
while(!path.empty()){
if(path[0]->left) path.push_back(path[0]->left);
if(path[0]->right) path.push_back(path[0]->right);
path.erase(path.begin());
count--;
if(count == 0 && path.size())
{
vector<int> tmp;
if(lefttoright){
vector<TreeNode*>::iterator it = path.begin();
for(; it != path.end(); ++it)
tmp.push_back((*it)->val);
lefttoright = false;
}else{
vector<TreeNode*>::iterator it = path.end();
for(--it;it>=path.begin();--it)
tmp.push_back((*it)->val);
lefttoright = true;
}
matrix.push_back(tmp);
count = path.size();
}
}
return matrix;
}
};