二叉树的锯齿层序遍历

思路:看到这道题的思路是,层序遍历 然后如何达到题目中说的锯齿的要求就是,用一个数字的与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;
    }
}
相关推荐
澈2072 小时前
二叉搜索树:高效增删查的秘诀
java·开发语言·算法
无敌昊哥战神2 小时前
大模型(LLM)推理优化技术全景总结
python·算法·大模型
平行侠2 小时前
A10 恶劣环境传感器信号仿真与统计检验台
算法
洛水水2 小时前
【力扣100题】34.二叉搜索树中第K小的元素
c++·算法·leetcode
_深海凉_2 小时前
LeetCode热题100-翻转二叉树
算法·leetcode·职场和发展
吃好睡好便好2 小时前
在Matlab中绘制抛物三维曲面图
开发语言·人工智能·学习·算法·matlab·信息可视化
tyung2 小时前
用 Go 实现一个生产级 Ring Buffer Queue:环形数组、位运算取模、批量操作全拆解
数据结构·go
伯远医学2 小时前
Nat. Methods | 邻近标记技术:活细胞中捕捉分子互作的新利器
java·开发语言·前端·javascript·人工智能·算法·eclipse
刘永鑫Adam3 小时前
Nature Microbiology | 基于TRACS算法的跨多界宏基因组数据菌株水平溯源推演
算法