给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回锯齿形层次遍历如下:
[ [3], [20,9], [15,7] ]
思路
一开始还没想到reverse,结果就很难办,估计要靠queue 和 stack才行。看到reverse以后目瞪口呆。。。
code
/**
* Definition for a binary tree node.
* 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) {
queue<TreeNode*> q;
vector<vector<int>> all;
if(!root)
return all;
q.push(root);
bool flag=0;
while(!q.empty()){
int len = q.size();
vector<int> aaa;
for(int i=0;i<len;i++){
TreeNode *p=q.front();q.pop();
aaa.push_back(p->val);
if(p->left)
q.push(p->left);
if(p->right)
q.push(p->right);
}
if(flag)
reverse(aaa.begin(),aaa.end());
flag=1-flag;
all.push_back(aaa);
}
return all;
}
};