二叉树的锯齿层序遍历

思路:看到这道题的思路是,层序遍历 然后如何达到题目中说的锯齿的要求就是,用一个数字的与2除模来确定当前的行数是单数行还是偶数行,如果是单数行则先存根节点的右子节点,然后再存根节点的左子节点。即偶数行是倒序的。

首先补充知识:反转动态list数组的方法是 Collections.reverse();

记住!!!!题目没有说为非空二叉树一定要提前判断是否是空!!!!

一开始的错误代码和调试

修改过后的代码:

复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        Deque<TreeNode> que = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        que.offer(root);
        int count = 0;
        if( root == null){
            return res;
        }
        while(!que.isEmpty()){
                count++;
                int size = que.size();
                List<Integer> list = new ArrayList<>();
            while(size > 0){
                TreeNode cur = que.poll();
                list.add(cur.val);
                size--;
                if(size == 0){
                    if(count % 2 == 0){
                    Collections.reverse(list);
                    }
                    res.add(list);
                }
                if(cur.left != null){
                    que.offer(cur.left);
                }
                if(cur.right != null){
                    que.offer(cur.right);
                }
            }
        }
        return res;
    }
}
相关推荐
IronMurphy16 分钟前
【算法五十七】146. LRU 缓存
算法·缓存
Irissgwe34 分钟前
数据结构-栈和队列
数据结构·c++·c·栈和队列
两片空白44 分钟前
数据容器集合set/frozenset
数据结构
凌波粒1 小时前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle1 小时前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
浦信仿真大讲堂1 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
点云侠1 小时前
PCL 生成三棱锥点云
c++·算法·最小二乘法
代码中介商1 小时前
跳表:高效查找的链表黑科技
数据结构
兰令水2 小时前
leecodecode【面试150】【2026.6.13打卡-java版本】
java·算法·leetcode
临沂堇2 小时前
刷题日志 | Leetcode Hot 100 哈希
算法·leetcode·哈希算法