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);
        }
    }
}
相关推荐
皓月斯语44 分钟前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet1 小时前
树状结构在查询优化中的作用与实现细节7
算法
徐凤年_1 小时前
rog_map参数理解
算法
春日见1 小时前
算法与数据结构----哈希表
数据结构·人工智能·算法·机器学习·自动驾驶·哈希算法·散列表
叩码以求索2 小时前
统计按位或能得到最大值的子集数目(一)
数据结构·算法
tachibana22 小时前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
txzrxz2 小时前
单调队列讲解
数据结构·c++·算法·单调队列
不会就选b3 小时前
算法日常・每日刷题--<快排>4
算法
Keven_113 小时前
算法札记:树状数组的用途
数据结构·算法
用户677437175813 小时前
C++函数参数传递方式详解:string、string&、const string、const string&该怎么选?
算法