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);
        }
    }
}
相关推荐
小陈phd16 分钟前
QAnything 阅读优化策略03——查询转换
算法
良木生香30 分钟前
【C++初阶】STL—— Stack & Queue 从入门到精通:容器适配器、迭代器与经典面试题
java·开发语言·c++·算法·zookeeper
小小晓.42 分钟前
C++小白记:vector
开发语言·c++·算法
tkevinjd44 分钟前
力扣72-编辑距离
算法·leetcode·职场和发展
小刘学技术1 小时前
AI人工智能决策树分类器:原理、实现与应用
开发语言·人工智能·python·算法·决策树·机器学习·数据挖掘
caimouse1 小时前
mm学习笔记_04:VAD树算法与地址空间分配
笔记·学习·算法·reactos
abcy0712132 小时前
flink窗口类型
开发语言·python·算法
什巳12 小时前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
什巳14 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_7968265215 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode