优选算法_锯齿形层序遍历二叉树_队列_C++

一.题目解析

就相当于蛇形遍历二叉树

算法解析:

二.代码编写:

cpp 复制代码
/**
 * 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) {
        vector<vector<int>>ret;
        if(root==nullptr)return ret;
        queue<TreeNode*>q;
        q.push(root);
        int level=1;
        while(!q.empty())
        {
            int sz=q.size();
            vector<int>tmp;
            
            for(int i=0;i<sz;i++)
            {
                TreeNode*t=q.front();
                q.pop();
                tmp.push_back(t->val);

                if(t->left)q.push(t->left);//左右孩子要入队
                if(t->right)q.push(t->right);
            }
            if(level%2==0)reverse(tmp.begin(),tmp.end());
            level++;
            ret.push_back(tmp);
        }
        return ret;
    }
};
相关推荐
si莉亚1 小时前
2026.3.31成功安装Ubuntu22.04+ROS2记录
linux·c++·开源
八宝粥大朋友1 小时前
Android sqlite3 编译及安装
android·java·sqlite
wxm6312 小时前
TCP监听--监听指定IP的端口号
java·网络·tcp/ip
秃头狂魔2 小时前
【HOT100】DAY2
python·算法
csdn2015_2 小时前
java 把对象转化为json字符串
java·前端·json
想带你从多云到转晴2 小时前
03、数据结构与算法--单向链表
java·数据结构·算法
Elnaij2 小时前
从C++开始的编程生活(24)——C++11标准Ⅰ
开发语言·c++
无籽西瓜a2 小时前
【西瓜带你学设计模式 | 第七期 - 适配器模式】适配器模式 —— 类适配器与对象适配器实现、优缺点与适用场景
java·后端·设计模式·软件工程·适配器模式
mjhcsp2 小时前
AT_arc205_c [ARC205C] No Collision Moves 题解
开发语言·c++·算法·题解