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);
        }
    }
}
相关推荐
luj_176815 分钟前
一线一区一变破解人盯人防守密码
开发语言·网络·c++·经验分享·算法
Wang's Blog38 分钟前
Java框架快速入门: Spring Security+OAuth2之字段验证与自定义验证注解实战
java·算法·spring
带多刺的玫瑰43 分钟前
Leecode#29刷题之两数相除
java·python·算法
smj2302_796826521 小时前
解决leetcode第4017题数组中的峰值II
python·算法·leetcode
午彦琳1 小时前
2026.9.9
数据结构·算法·leetcode
luj_17681 小时前
中锋卡位与开放线博弈
c语言·开发语言·网络·经验分享·算法
洋不写bug1 小时前
二叉树(四)经典算法题目解析,公共祖先,二叉树构造,非递归遍历
数据库·算法·二叉树·二叉树构造·公共祖先
hansang_IR1 小时前
【题解】P4454 [CQOI2018] 破解D-H协议
c++·算法·密码学·数论
梓䈑1 小时前
【动态规划系列】路径问题、子数组 和 子序列问题、背包问题
c++·算法·动态规划
aqiu1111111 小时前
【数位 DP / 记忆化搜索】蓝桥云课 - 光轨区的 AI 数 题解
c++·算法·蓝桥杯·数位dp