二叉树的锯齿层序遍历

思路:看到这道题的思路是,层序遍历 然后如何达到题目中说的锯齿的要求就是,用一个数字的与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;
    }
}
相关推荐
threerocks8 分钟前
Jev 入门第一课
算法
西柚研究生1234561 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
hetao17338372 小时前
2026-09-17 hetao1733837 的刷题记录
c++·算法
午彦琳3 小时前
2026.9.17
数据结构·算法·leetcode
木井巳3 小时前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法
怕浪猫4 小时前
从 Windows 换到 Mac 三个月,我真香了
算法·面试·架构
aichitang20245 小时前
前端小skill
前端·人工智能·算法·ai·前端框架
All for pursuit.6 小时前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
木子算法6 小时前
测出来的值会抖:约束和目标带噪声时,「可行」和「更好」该怎么判
人工智能·算法·目标跟踪
hanlin037 小时前
刷题笔记:力扣第144题-二叉树的前序遍历
笔记·算法·leetcode