LeetCode.107. 二叉树的层序遍历 II

题目

107. 二叉树的层序遍历 II

分析

这个题目考查的是二叉树的层序遍历,对于二叉树的层序遍历,我们需要借助 队列 这种数据结构。再来回归本题 ,我们只需要将 二叉树的层序遍历的结果逆序,就可以得到这道题我们要求的答案了。接下来我们的难题就是如何实现二叉树的层序遍历了

以例一为例子:

这个二叉树的层序遍历为 [ [3] , [9,20] , [15,7] ]。

怎么实现呢?

首先将根节点放入队列,判断队列是否为空,如果不为空记录当前队列的元素个数(这个个数就是这一层的所有元素),借助一个中间容器存放当前层的元素list,遍历这一层的所有元素放入list中,并且将这一层每一个元素的左右孩子如果不为空放入队列里面。

下面画图展示一下:

代码

java 复制代码
/**
 * 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>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while(size != 0) {
                size--;
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null) queue.add(node.left);
                if(node.right != null) queue.add(node.right);
            }
            res.add(list);
        }
        Collections.reverse(res);
        return res;
    }
}
相关推荐
无糖冰可乐212 小时前
IDEA多java版本切换
java·ide·intellij-idea
合作小小程序员小小店2 小时前
web开发,在线%超市销售%管理系统,基于idea,html,jsp,java,ssh,sql server数据库。
java·前端·sqlserver·ssh·intellij-idea
brucelee1862 小时前
IntelliJ IDEA 设置 Local History 永久保留
java·ide·intellij-idea
Pluto_CSND4 小时前
Java中的静态代理与动态代理(Proxy.newProxyInstance)
java·开发语言
百***46455 小时前
Java进阶-在Ubuntu上部署SpringBoot应用
java·spring boot·ubuntu
serve the people5 小时前
Prompts for Chat Models in LangChain
java·linux·langchain
一叶飘零_sweeeet5 小时前
不止于 API 调用:解锁 Java 工具类设计的三重境界 —— 可复用性、线程安全与性能优化
java·工具类
cynicme6 小时前
力扣3228——将 1 移动到末尾的最大操作次数
算法·leetcode
熬了夜的程序员6 小时前
【LeetCode】109. 有序链表转换二叉搜索树
数据结构·算法·leetcode·链表·职场和发展·深度优先
随意起个昵称6 小时前
【递归】二进制字符串中的第K位
c++·算法