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;
    }
};
相关推荐
I_LPL几秒前
day34 代码随想录算法训练营 动态规划专题2
java·算法·动态规划·hot100·求职面试
汉克老师1 分钟前
GESP2024年3月认证C++二级( 第一部分选择题(9-15))
c++·循环结构·分支结构·gesp二级·gesp2级
We་ct16 分钟前
LeetCode 105. 从前序与中序遍历序列构造二叉树:题解与思路解析
前端·算法·leetcode·链表·typescript
万象.1 小时前
redis集群算法,搭建,故障处理及扩容
redis·算法·哈希算法
plus4s1 小时前
2月19日(85-87题)
c++·算法
白太岁1 小时前
Redis:(2) hiredis 使用、C++ 封装与连接池
c语言·c++·redis·缓存
Desirediscipline1 小时前
cerr << 是C++中用于输出错误信息的标准用法
java·前端·c++·算法
Renhao-Wan1 小时前
Java 算法实践(八):贪心算法思路
java·算法·贪心算法
汉克老师1 小时前
GESP2024年6月认证C++二级( 第三部分编程题(2)计数 )
c++·循环结构·枚举算法·gesp二级·gesp2级·数字拆分
王老师青少年编程2 小时前
2020年信奥赛C++提高组csp-s初赛真题及答案解析(选择题11-15)
c++·题解·真题·初赛·信奥赛·csp-s·提高组