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);
        }
    }
}
相关推荐
没有钱的钱仔5 小时前
协方差矩阵含义
算法·机器学习·矩阵
垆边人似月.5 小时前
华为机试题 :和为 K 的子数组个数
算法·leetcode·华为
三*一6 小时前
优化修整算法
前端·javascript·算法
达子6666 小时前
RUST 图解 第 3 章:通用编程概念(Common Programming Concepts)
开发语言·算法·rust
夏幻灵6 小时前
每日一题:LeetCode 165:比较版本号
算法·leetcode·职场和发展
道尔柯南6 小时前
C++ 面向对象编程入门:类和对象(上)
开发语言·c++·算法
Navigator_Z7 小时前
LeetCode //C - 1288. Remove Covered Intervals
c语言·算法·leetcode
码爸7 小时前
决策树介绍与示例
python·算法·机器学习
动词ing7 小时前
【题目练习】字符串相乘
算法