题目描述
给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
该二叉树之字形层序遍历的结果是
[
[3],
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
// write code here
deque<TreeNode*> dq;
vector<vector<int>> res;
if (root ==NULL) return res;
dq.push_back(root);
int dir = 0;
int size;
while(dq.size()) {
vector<int> vec;
size = dq.size();
while (size-- > 0) {
if (dir % 2==0) {
TreeNode* x = dq.front();
dq.pop_front();
TreeNode *left = x->left;
TreeNode *right = x->right;
vec.push_back(x->val);
if (left) dq.push_back(left);
if (right) dq.push_back(right);
}else{
TreeNode* x = dq.back();
dq.pop_back();
TreeNode * left = x ->left;
TreeNode * right = x->right;
if (right) dq.push_front(right);
if (left) dq.push_front(left);
vec.push_back(x -> val);
}
}
res.push_back(vec);
++dir;
}
return res;
}
};