Leetcode103. 二叉树的锯齿形层序遍历 -春招冲刺

题目:


代码(首刷自解 2024年4月12日):

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        vector<int> path;
        if (!root) return res;
      
        queue<TreeNode*> q;
        q.push(root);
        int count = 1;
        while(!q.empty()) {
            int size = q.size();
            path.clear();
            count++;//奇数 左往右 偶数 右往左
            while (size--) {
                TreeNode* node = q.front();
                if (!(count & 1)) {
                    path.push_back(node->val);
                } else {
                    path.insert(path.begin(), node->val);
                }
                q.pop();
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
            res.push_back(path);
        }
        return res;
    }
};

代码(二刷debug看解析 2024年8月5日)

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        // 队列存Node
        vector<vector<int>> res;
        if (!root) return res; 
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int size = q.size();
            vector<int> temp;
            temp.reserve(size);
            while(size--) {
                auto node = q.front();
                q.pop();
                if (0 == (res.size() & 1)) {
                    temp.emplace_back(node->val);
                } else {
                    temp.insert(temp.begin(), node->val);
                }
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
            res.push_back(temp);
        }
        return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值