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);
        }
    }
}
相关推荐
Savior`L2 小时前
二分算法及常见用法
数据结构·c++·算法
mmz12073 小时前
前缀和问题(c++)
c++·算法·图论
努力学算法的蒟蒻3 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
甄心爱学习4 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~4 小时前
排序---常用排序算法汇总
数据结构·算法·排序算法
AndrewHZ5 小时前
【遥感图像入门】DEM数据处理核心算法与Python实操指南
图像处理·python·算法·dem·高程数据·遥感图像·差值算法
CoderYanger5 小时前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节
有时间要学习5 小时前
面试150——第二周
数据结构·算法·leetcode
liu****5 小时前
3.链表讲解
c语言·开发语言·数据结构·算法·链表