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);
        }
    }
}
相关推荐
AI备案指南-满满2 小时前
人工智能拟人化互动服务安全自评估报告的评估要点有哪些?
人工智能·算法·安全·机器人·大模型备案·算法备案
土司大王3 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
大熊背4 小时前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc
zander2585 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲5 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
祖力555 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜5 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者5 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
圣保罗的大教堂6 小时前
leetcode 3622. 判断整除性 简单
leetcode