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;
    }
};
相关推荐
放荡不羁的野指针10 分钟前
leetcode150题-字符串
数据结构·算法·leetcode
苦藤新鸡13 分钟前
4.移动零
c++·算法·力扣
hetao173383720 分钟前
2026-01-04~06 hetao1733837 的刷题笔记
c++·笔记·算法
橘颂TA24 分钟前
【剑斩OFFER】算法的暴力美学——存在重复元素Ⅱ
算法·leetcode·哈希算法·散列表·结构与算法
Boilermaker199226 分钟前
[算法基础] DFS
算法
bubiyoushang88829 分钟前
MATLAB比较SLM、PTS和Clipping三种算法对OFDM系统PAPR的抑制效果
数据结构·算法·matlab
cg501736 分钟前
力扣数据库——组合两个表
sql·算法·leetcode
六边形战士DONK37 分钟前
[强化学习杂记] 从数学角度理解贝尔曼最优公式为什么是greedy?
算法
C雨后彩虹44 分钟前
计算误码率
java·数据结构·算法·华为·面试
2501_941798731 小时前
面向微服务分布式事务补偿与最终一致性的互联网系统高可用设计与多语言工程实践分享
leetcode·模拟退火算法