leetcode 103. 二叉树的锯齿形层次遍历 medium
题目描述:
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
解题思路:
正常的两个循环层序,最后把奇数行逆序一下
代码:
/**
* 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) {
if(!root)
return {};
vector<vector<int>> res;
using node = TreeNode;
queue<node *> q1{{root}};
node *cur=nullptr;
while(q1.size()){
vector<int> onelevel;
for(int i=q1.size();i>0;--i){
cur=q1.front();
q1.pop();
onelevel.push_back(cur->val);
if(cur->left) q1.push(cur->left);
if(cur->right) q1.push(cur->right);
}
res.push_back(onelevel);
}
for(int i=1;i<=res.size()-1; i += 2){
reverse(res[i].begin(),res[i].end());
}
return res;
}
};