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) {
vector<vector<int>> rst;
BFS(root,0,rst);
for(int i=1;i<rst.size();i+=2){
reverse(rst[i].begin(),rst[i].end());
}
return rst;
}
void BFS(TreeNode *root, int level, vector<vector<int> > &rst) {
if(!root)return ;
if(level>=rst.size()) rst.push_back(vector<int>());
rst[level].push_back(root->val);
BFS(root->left,level+1,rst);
BFS(root->right,level+1,rst);
}
};