zoukankan      html  css  js  c++  java
  • [leetcode] 107. 二叉树的层次遍历 II

    107. 二叉树的层次遍历 II

    相当于把102. 二叉树的层次遍历的输出结果反转了一下

    class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> lists = levelOrder(root);
            Collections.reverse(lists);
            return lists;
        }
        
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> list = new ArrayList<>();
            if (root == null) return list;
            LinkedList<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
    
            TreeNode flag = root;
            List<Integer> nowNumList = new ArrayList<>();
            list.add(nowNumList);
    
            while (!queue.isEmpty()) {
                TreeNode nowNode = queue.poll();
                nowNumList.add(nowNode.val);
    
                TreeNode sonNode = nowNode.left;
                if (sonNode != null) queue.offer(sonNode);
    
                sonNode = nowNode.right;
                if (sonNode != null) queue.offer(sonNode);
    
                if (flag == nowNode && !queue.isEmpty()) {//判断当前元素是否为本层最后一个节点。注意要判断当处于最后一层的时候不执行,否则会添加一个空的list
                    nowNumList = new ArrayList<>();
                    list.add(nowNumList);
                    flag = queue.peekLast();//更新标记
                }
            }
            return list;
        }
    }
    
  • 相关阅读:
    Kruskal算法
    拓扑排序
    邻接表有向图
    邻接矩阵的有向图
    邻接表无向图
    邻接矩阵无向图
    斐波那契堆
    二项堆
    斜堆(待补充)
    项目中maven依赖无法自动下载
  • 原文地址:https://www.cnblogs.com/acbingo/p/9917722.html
Copyright © 2011-2022 走看看