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;
    }
};
相关推荐
ryanuo71 分钟前
Shadcn/ui × Qt 6/QML:一次从 Web UI 到桌面 UI 的组件化实践
c++·qt·ui·shadcn
余额瞒着我当琳3 分钟前
C++--vector第二讲:手写 C++ STL:vector 源码剖析与迭代器失效分析
android·java·c++
一只积极向上的小咸鱼4 分钟前
分词器tokenizer
算法·llm
Elsa️74613 分钟前
leetcode 14.最长公共前缀
算法·leetcode·职场和发展
郝学胜-神的一滴15 分钟前
[简化版 GAMES 104] 现代游戏引擎 06:从Tick时序到邮局模型,拆解确定性世界的底层密码
开发语言·c++·游戏引擎·图形渲染·软件开发·opengl
不会代码的小猴16 分钟前
6. Qt网络编程
开发语言·c++·笔记·qt·算法
沐风老师19 分钟前
从零开始学3dMax插件开发!
c++·3dmax插件·3dmax·maxscript
Zguigo28 分钟前
树的前序|中序|后序遍历【使用栈实现】
数据结构·算法
zhanghaha13141 小时前
HTML系列教程:4_什么是 HTML 元素(零基础超详细讲解)
前端·算法·html
TAN-90°-1 小时前
Deep Learning for Computer Vision——Training CNNs and CNN Architectures
人工智能·深度学习·神经网络·算法·机器学习·计算机视觉·cnn