二叉树的锯齿层序遍历

思路:看到这道题的思路是,层序遍历 然后如何达到题目中说的锯齿的要求就是,用一个数字的与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;
    }
}
相关推荐
玖玥拾2 小时前
LeetCode 125 验证回文串
算法·leetcode
Asize9 小时前
146. LRU 缓存
算法
Asize9 小时前
543. 二叉树的直径
算法
lemon_sjdk9 小时前
ObjectProperty
java·开发语言·算法
Zentceh9 小时前
AI-ISP在夜视机芯中的应用:从传统ISP到PixelClean全彩夜视的进化
人工智能·科技·算法·计算机视觉·车载系统·视频·智能硬件
xier_ran9 小时前
【infra之路】AWQ 详解:激活感知权重保护,让 W4A16 量化精度超越 GPTQ
线性代数·算法·机器学习·量化·infra
亦皓ai10 小时前
AI时代后端工程(二):AI把代码写得越来越快,我却越来越不敢让它直接开工了
人工智能·算法·机器学习·搜索引擎·transformer
玖玥拾11 小时前
LeetCode 392 判断子序列
笔记·算法·leetcode
不灭的黄金瞳12312 小时前
C语言手写顺序表
c语言·开发语言·数据结构
qeen8712 小时前
【数据结构】哈希表的C++实现与封装
数据结构·c++·散列表·哈希表