# 二叉树的锯齿形层序遍历

给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回锯齿形层序遍历如下:

[
  [3],
  [20,9],
  [15,7]
]
## template ```cpp #include using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector> zigzagLevelOrder(TreeNode *root) { if (!root) return {}; vector> res; vector temp; int level = 0; queue> q; q.push(pair(root, 0)); while (!q.empty()) { TreeNode *node = q.front().first; level = q.front().second; q.pop(); if (res.size() < level) { if (level % 2 == 0) reverse(temp.begin(), temp.end()); res.push_back(temp); temp.clear(); } temp.push_back(node->val); if (node->left) q.push(pair(node->left, level + 1)); if (node->right) q.push(pair(node->right, level + 1)); } if (level % 2 != 0) reverse(temp.begin(), temp.end()); res.push_back(temp); return res; } }; ``` ## 答案 ```cpp ``` ## 选项 ### A ```cpp ``` ### B ```cpp ``` ### C ```cpp ```