二叉树算法之【Z字型层序遍历】

目录

LeetCode-103题


LeetCode-103题

给定一个二叉树的根节点root,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)

java 复制代码
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        // check
        if (root == null)
            return result;
        // 借助队列来实现
        Queue<TreeNode> queue = new LinkedList<>();
        // 先将根节点放到队列中
        queue.offer(root);
        // 用于记录当前层的节点数量
        int c1 = 1;
        // 用于标识添加方向
        int flag = 1;
        // 只要队列不为空
        while (!queue.isEmpty()) {
            // 用于记录下一层节点数量
            int c2 = 0;
            LinkedList<Integer> inner = new LinkedList<>();
            for (int i = 0; i < c1; i++) {
                TreeNode curr = queue.poll();
                // 根据标识判断addLast还是addFirst
                if (flag % 2 == 1) {
                    inner.addLast(curr.val);
                } else {
                    inner.addFirst(curr.val);
                }
                // 有左子节点
                if (curr.left != null) {
                    // 将左子节点添加到队列中
                    queue.offer(curr.left);
                    // 记录下一层节点数量标识+1
                    c2++;
                }
                // 有右子节点
                if (curr.right != null) {
                    // 将右子节点添加到队列中
                    queue.offer(curr.right);
                    // 记录下一层节点数量标识+1
                    c2++;
                }
            }
            // 下一轮遍历通过c1就知道当前层有多少个节点了
            c1 = c2;
            // 下一层换个方向,以达到Z字形
            flag++;
            result.add(inner);
        }
        return result;
    }
}
相关推荐
weixin_3993806915 小时前
TongWeb+TongDataGrid+TongHttpServer实现Session复制
java·tomcat
青云交15 小时前
Java 大视界 -- Java+Flink CDC 构建实时数据同步系统:从 MySQL 到 Hive 全增量同步(443)
java·mysql·flink·实时数据同步·java+flink cdc·mysql→hive·全增量同步
闻缺陷则喜何志丹15 小时前
【图论 DFS 换根法】3772. 子图的最大得分|2235
c++·算法·深度优先·力扣·图论·换根法
开开心心就好15 小时前
音频格式互转工具,支持Mp3ApeWavFlac互转
java·网络·c++·windows·qt·电脑·excel
Java猿_15 小时前
开发 Java 项目,选哪个 IDE?Eclipse、MyEclipse 与 IntelliJ IDEA 深度对比
java·ide·eclipse
Icarus_15 小时前
IDEA Android studio 快捷鍵
java·android studio·intellij-idea
小罗和阿泽15 小时前
Java项目 简易图书管理系统
java·开发语言
一只大侠的侠15 小时前
Python实现TTAO算法:优化神经网络中的时序预测任务
python·神经网络·算法
a程序小傲15 小时前
【Node】单线程的Node.js为什么可以实现多线程?
java·数据库·后端·面试·node.js
indexsunny18 小时前
互联网大厂Java求职面试实战:Spring Boot微服务与Redis缓存场景解析
java·spring boot·redis·缓存·微服务·消息队列·电商