LeetCode-107-二叉树的层序遍历Ⅱ

题目描述:

给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

题目链接:LeetCode-107-二叉树的层序遍历Ⅱ

解题思路:和 LeetCode-102-二叉树的层序遍历 完全一样,只是最后一句每次都查到最前面.
代码实现:

java 复制代码
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        bfs(root);
        return res;
    }

    List<List<Integer>> res = new LinkedList<>();

    private void bfs(TreeNode node) {
        if (node == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(node);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> path = new ArrayList<>();
            while (size > 0) {
                // 弹出队列中的一个元素
                TreeNode tmp = queue.poll();
                path.add(tmp.val);
                if (tmp.left != null) {
                    queue.add(tmp.left);
                }
                if (tmp.right != null) {
                    queue.offer(tmp.right);
                }
                size--;
            }
            // 收获结果,和 102题 完全一样,只是最后一句每次都查到最前面
            res.add(0, path);
        }
    }
}
相关推荐
wzdark4 分钟前
动态规划算法的状态转移矩阵可视化分析5
算法·矩阵·动态规划
Pniubi8 分钟前
力扣70爬楼梯
数据结构·算法·leetcode
人工智能培训13 分钟前
具身智能环境交互与学习范式原理
大数据·linux·人工智能·学习·算法·机器学习
纪念 2291 小时前
C++算法(三)
开发语言·c++·算法
学不会pwn不改名1 小时前
时间复杂度与空间复杂度详解
算法
AbandonForce1 小时前
递归、搜索与回溯:从板书到二叉树解题方法
c++·算法·决策树
打工仔折腾 AI2 小时前
让时序预测真正参与决策:TimechoAI 工程化落地与管线设计实践
人工智能·后端·python·算法·机器学习·性能优化
Light602 小时前
企业自建 AI 智能体,成本差 8 倍还是 46 倍?
java·人工智能·算法·知识图谱·rag·ai agent 上下文·token 成本
曹牧2 小时前
VS: Visual Studio 里把未包含的文件加进项目2
linux·运维·算法