LeetCode103. Binary Tree Zigzag Level Order Traversal

文章目录

一、题目

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

Example 1:

Input: root = [3,9,20,null,null,15,7]

Output: [[3],[20,9],[15,7]]

Example 2:

Input: root = [1]

Output: [[1]]

Example 3:

Input: root = []

Output: []

Constraints:

The number of nodes in the tree is in the range [0, 2000].

-100 <= Node.val <= 100

二、题解

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>> res;
        queue<TreeNode*> q;
        if(!root) return res;
        q.push(root);
        int level = 0;
        while(!q.empty()){
            int size = q.size();
            vector<int> tmp;
            while(size--){
                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 == 1){
                reverse(tmp.begin(),tmp.end());
                res.push_back(tmp);
            }
            else res.push_back(tmp);
            level++;
        }
        return res;
    }
};
相关推荐
nlpming34 分钟前
OpenCode Skills 文档
算法
无限进步_36 分钟前
二叉搜索树完全解析:从概念到实现与应用场景
c语言·开发语言·数据结构·c++·算法·github·visual studio
鱼跃厂长43 分钟前
这份skill,能将你的简历提升到字节的水平!
c++·ai·ai编程
05候补工程师44 分钟前
深度解构 ROS 2:如何手动调通 Nav2 A* 路径规划引擎
linux·人工智能·经验分享·算法·机器人
上弦月-编程1 小时前
【C语言逻辑题】谋杀案凶手是谁?——经典矛盾推理题详解
算法
天若有情6731 小时前
逆向玩家狂喜!用C++野生写法一键破解线性加密(不规范但巨好用)
开发语言·c++·算法
咸鱼翻身小阿橙1 小时前
Qt QML调用C++注册类
java·c++·qt
风筝在晴天搁浅2 小时前
剑指Offer 60.n个骰子的点数
算法
ProgramHelpOa2 小时前
Optiver 2026 OA 全面复盘|26NG / Intern 最新高频题型整理
人工智能·算法·机器学习