给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)
样例
给出一棵二叉树 {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
返回其锯齿形的层次遍历为:
[
[3],
[20,9],
[15,7]
]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > vec;
if(!root)
return vec;
bool open=false;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
int count=que.size();
vector<int> base;
while(count--){
TreeNode *tmp=que.front();
que.pop();
base.push_back(tmp->val);
if(tmp->left)
que.push(tmp->left);
if(tmp->right)
que.push(tmp->right);
}
if(open)
reverse(base.begin(),base.end());
open=!open;
vec.push_back(base);
}
return vec;
}
};