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;
    }
};
相关推荐
坚果派·白晓明5 小时前
【鸿蒙PC】SDL3 适配:AtomCode + Skills 快速集成 NAPI 测试工具
c++·华为·ai编程·harmonyos·atomcode
云絮.6 小时前
数据库操作
数据库·mysql·算法·oracle
小林ixn6 小时前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
凡人叶枫6 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
凡人叶枫7 小时前
Effective C++ 条款16:成对使用 new 和 delete 时要采取相同形式
开发语言·c++·effective c++
菜鸟‍7 小时前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
不吃土豆的马铃薯8 小时前
C++ 高性能网络缓冲区 Buffer 源码解析
linux·服务器·开发语言·网络·c++
.千余8 小时前
【C++】C++继承入门(下):友元、静态成员与菱形继承的底层逻辑
开发语言·c++·笔记·学习·其他
初中就开始混世的大魔王8 小时前
6 Fast DDS-传输层
开发语言·c++·中间件·信息与通信
退休倒计时9 小时前
【每日一题】LeetCode 142. 环形链表 II TypeScript
算法·leetcode·链表·typescript