给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:[
[3],
[20,9],
[15,7]
]
解法:
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root)
{
if(!root) return {};
vector<vector<int>> res;
queue<TreeNode *> qu;
qu.push(root);
int n = 0;
while(!qu.empty())
{
int count = qu.size();
vector<int> curr;
while(count--)
{
TreeNode *s = qu.front();
qu.pop();
curr.push_back(s->val);
if(s->left) qu.push(s->left);
if(s->right) qu.push(s->right);
}
++n;
if(n % 2 == 0)
std::reverse(curr.begin(), curr.end());
res.push_back(curr);
}
return res;
}
};