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;
    }
};
相关推荐
万能程序员-传康Kk16 分钟前
旅游推荐数据分析可视化系统算法
算法·数据分析·旅游
PXM的算法星球21 分钟前
【并发编程基石】CAS无锁算法详解:原理、实现与应用场景
算法
ll77881121 分钟前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
烨然若神人~24 分钟前
算法第十七天|654. 最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树
算法
爱coding的橙子35 分钟前
每日算法刷题Day2 5.10:leetcode数组1道题3种解法,用时40min
算法·leetcode
我不想当小卡拉米38 分钟前
【Linux】操作系统入门:冯诺依曼体系结构
linux·开发语言·网络·c++
Akiiiira43 分钟前
【数据结构】栈
数据结构
炎芯随笔1 小时前
【C++】【设计模式】生产者-消费者模型
开发语言·c++·设计模式
阳洞洞1 小时前
leetcode 18. 四数之和
leetcode·双指针
乌鸦9441 小时前
《类和对象(下)》
开发语言·c++·类和对象+