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;
    }
};
相关推荐
2301_807997381 分钟前
代码随想录-day26
数据结构·c++·算法·leetcode
闭着眼睛学算法10 分钟前
【双机位A卷】华为OD笔试之【排序】双机位A-银行插队【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
java·c语言·javascript·c++·python·算法·华为od
TL滕11 分钟前
从0开始学算法——第一天(认识算法)
数据结构·笔记·学习·算法
小欣加油13 分钟前
leetcode 3318 计算子数组的x-sum I
c++·算法·leetcode·职场和发展
love is sour30 分钟前
聚类(Clustering)详解:让机器自己发现数据结构
算法·支持向量机·聚类
烟袅38 分钟前
LeetCode 142:环形链表 II —— 快慢指针定位环的起点(JavaScript)
前端·javascript·算法
CoovallyAIHub42 分钟前
OCR战场再起风云:LightOnOCR-1B凭什么比DeepSeekOCR快1.7倍?(附演示开源地址)
深度学习·算法·计算机视觉
j_xxx404_1 小时前
C++ STL:list|了解list|相关接口|相关操作
开发语言·c++
kyle~1 小时前
机器视觉---Intel RealSense SDK 2.0 开发流程
运维·c++·windows·深度相机·intel realsense
海琴烟Sunshine1 小时前
leetcode 190. 颠倒二进制位 python
python·算法·leetcode