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;
    }
}
相关推荐
装不满的克莱因瓶16 分钟前
【从零搭建】AI大模型之ReactAgent智能体对接MCP实战
java·人工智能·ai·springai·mcp·springaialibaba
kyle~1 小时前
因子图优化(Factor Graph Optimization)
c++·算法·机器人·传感器
SimonKing1 小时前
AI Assistant被"隐藏"了?别慌,IDEA 2026.3 这波是换了个脑子
java·后端·程序员
Resean02231 小时前
SpringMVC 6+源码分析(九)异常处理
java·spring·springmvc
geats人山人海1 小时前
现代c++4.1
java·开发语言·c++
Pniubi2 小时前
贪心算法入门
算法·贪心算法
MobotStone2 小时前
AI 能不能越用越会用?从“改答案”到“改进自己”,读懂 RSI
人工智能·算法
下一站春风里2 小时前
Spring IoC 控制反转 完整技术笔记
java·spring boot·笔记·spring
挖掘狂人2 小时前
用户连点两次「确认支付」,你的后端凭什么只扣一次钱?
java·后端·面试
codigger2 小时前
用户连点两次「确认支付」,你的后端凭什么只扣一次钱?
java·程序员·支付·java后端