Java | Leetcode Java题解之第103题二叉树的锯齿形层序遍历

题目:

题解:

java 复制代码
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<List<Integer>>();
        if (root == null) {
            return ans;
        }

        Queue<TreeNode> nodeQueue = new ArrayDeque<TreeNode>();
        nodeQueue.offer(root);
        boolean isOrderLeft = true;

        while (!nodeQueue.isEmpty()) {
            Deque<Integer> levelList = new LinkedList<Integer>();
            int size = nodeQueue.size();
            for (int i = 0; i < size; ++i) {
                TreeNode curNode = nodeQueue.poll();
                if (isOrderLeft) {
                    levelList.offerLast(curNode.val);
                } else {
                    levelList.offerFirst(curNode.val);
                }
                if (curNode.left != null) {
                    nodeQueue.offer(curNode.left);
                }
                if (curNode.right != null) {
                    nodeQueue.offer(curNode.right);
                }
            }
            ans.add(new LinkedList<Integer>(levelList));
            isOrderLeft = !isOrderLeft;
        }

        return ans;
    }
}
相关推荐
Hi李耶7 小时前
【LeetCode】15.三数之和
java·算法·leetcode
蔬菜_8 小时前
前端转全栈-day6(构造函数与继承)
java
程序员雷欧8 小时前
Java 反射深度解析:从原理到源码的全面剖析
java·开发语言·python
登登登__8 小时前
春秋招笔试题总结
java·开发语言
rannn_1118 小时前
【力扣hot100】链表专题|21、2、19、24、92、25
java·数据结构·算法·leetcode·链表·开发
鹿角片ljp8 小时前
LeetCode 21. 合并两个有序链表
算法·leetcode·链表
Rabitebla9 小时前
C++11 新特性详解(一):列表初始化、initializer_list 与右值引用
java·开发语言·数据结构·c++·算法·leetcode·list
洋不写bug9 小时前
JavaComparable、Comparator、Cloneable接口解析,深拷贝浅拷贝详细解析
android·java·开发语言
坐吃山猪9 小时前
WebFlux_学习Subscriber总结
java·开发语言·学习·webflux
白露与泡影9 小时前
Java面试题及答案整理(2026年金九银十最新版,持续更新)
java·开发语言