Leetcode|BFS+双端队列|103. 二叉树的锯齿形层序遍历

2021-09-22 10:56:14 浏览数 (1)

1 BFS 双端队列

代码语言:javascript复制
/**
 * 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 {};
        queue<TreeNode*> q;
        q.push(root);
        bool leftflag = true; // 从左至右标致
        vector<vector<int>> res;
        while (!q.empty()) {
            deque<int> lst;  // 双端队列,每层结束后需重置
            int sz = q.size();
            for (int i = 0; i < sz; i  ) {
                auto node = q.front(); q.pop();
                if (leftflag) lst.push_back(node->val);  // 若是从左至右,则顺序添加到双端队列中
                else lst.push_front(node->val);          // 若是从右至左,则逆序添加到双端队列中

                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
            res.push_back(vector<int>{lst.begin(), lst.end()});  // 最后将当前双端队列,顺序添加到res中,注意vector<int>强转类型
            leftflag = !leftflag; 
        }
        return res;
    }
};

0 人点赞