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几秒前
hot100 栈专题
算法·
小菜鸡桃蛋狗2 分钟前
C++——类和对象(上)
开发语言·c++
此生只爱蛋8 分钟前
【数据结构】红黑树
数据结构
2401_8795034112 分钟前
C++中的观察者模式变体
开发语言·c++·算法
阿贵---32 分钟前
C++中的备忘录模式
开发语言·c++·算法
Drone_xjw37 分钟前
Qt 工具箱需求文档
c++·qt·需求文档
setmoon2141 小时前
C++中的观察者模式实战
开发语言·c++·算法
2403_835568471 小时前
C++代码规范化工具
开发语言·c++·算法
tankeven1 小时前
HJ138 在树上游玩
c++·算法
北顾笙9801 小时前
测开准备-day01数据结构力扣
数据结构