LeetCode:103. 二叉树的锯齿形层序遍历

目录

题目描述:

代码:


这个与二叉树的层序遍历有点类似

题目描述:

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

示例 1:

复制代码
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[20,9],[15,7]]

示例 2:

复制代码
输入:root = [1]
输出:[[1]]

示例 3:

复制代码
输入:root = []
输出:[]

代码:

复制代码
   public List<List<Integer>> zigzaLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        LinkedListQueue<TreeNode> queue = new LinkedListQueue<TreeNode>();//单向环形哨兵链表
        queue.offer(root);
        int c1 = 1;//当前的节点数
        boolean odd = true;//奇数层
        while (!queue.isEmpty()) {
            LinkedList<Integer> level = new LinkedList<>();//每一层的节点  jdk自带的
            int c2 = 0;
            for (int i = 0; i < c1; i++) {
                TreeNode n = queue.poll();
               if(odd){  //奇数层从左到右
                   level.offerLast(n.val);//尾部插入
               }else{//偶数层从右到左
                   level.offerFirst(n.val);//头部插入
               }
                if (n.left != null) {
                    queue.offer(n.left);
                    c2++;
                }
                if (n.right != null) {
                    queue.offer(n.right);
                    c2++;
                }
            }
            odd = !odd;//取反
            res.add(level);
            c1 = c2;

        }
        return res;
    }
相关推荐
xushichao19896 分钟前
实时数据压缩库
开发语言·c++·算法
minji...8 分钟前
Linux 文件系统 (三) 软连接和硬链接
linux·运维·服务器·c++·算法
故事和你9125 分钟前
sdut-python-实验四-python序列结构(21-27)
大数据·开发语言·数据结构·python·算法
memcpy030 分钟前
LeetCode 1456. 定长子串中元音的最大数目【定长滑窗模板题】中等
算法·leetcode·职场和发展
liuyao_xianhui34 分钟前
优选算法_模拟_提莫攻击_C++
开发语言·c++·算法·动态规划·哈希算法·散列表
玛丽莲茼蒿1 小时前
LeetCode hot100【相交链表】【简单】
算法·leetcode·职场和发展
罗湖老棍子1 小时前
They Are Everywhere(Codeforces- P701C)
算法·滑动窗口·codeforce题解
wen__xvn1 小时前
力扣模拟题刷题
算法·leetcode
bbbb3651 小时前
算法复杂度与能耗关系的多变量分析研究的技术7
算法
不要秃头的小孩1 小时前
力扣刷题——111.二叉树的最小深度
数据结构·python·算法·leetcode