LeetCode 103. 二叉树的锯齿形层次遍历

发布时间 2023-05-22 13:30:17作者: 穿过雾的阴霾
class Solution {
public:
    vector<vector<int>> res;
    void bfs(TreeNode* root)
    {
        queue<TreeNode*> q;
        q.push(root);
        int cnt=0;
        while(!q.empty())
        {
            vector<int> level;
            int len=q.size();
            cnt++;
            while(len--)
            {
                auto t=q.front();
                q.pop();
                level.push_back(t->val);
                if(t->right)    q.push(t->right);
                if(t->left)    q.push(t->left);
            }
            if(cnt&1)   reverse(level.begin(),level.end());
            res.push_back(level);
        }
        return;
    }
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if(!root)   return res;
        bfs(root);
        return res;
    }
};