103. 二叉树的锯齿形层序遍历
解法1:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root)
{
if(!root) return {};
vector<vector<int>> res;
queue<TreeNode *> qu;
qu.push(root);
int cnt = 0;
while(!qu.empty())
{
++cnt;
int num = qu.size();
vector<int> temp;
while(num--)
{
auto p = qu.front();
qu.pop();
temp.push_back(p->val);
if(p->right) qu.push(p->right);
if(p->left) qu.push(p->left);
}
if(cnt%2)
reverse(temp.begin(), temp.end());
res.push_back(temp);
}
return res;
}
};