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);
        }
    }
}
相关推荐
故事和你919 小时前
洛谷-算法2-3-分治与倍增5
开发语言·数据结构·c++·算法·动态规划·图论
北顾笙9809 小时前
day37-数据结构力扣
数据结构·算法·leetcode
啦啦啦_99999 小时前
1. 逻辑回归
算法·机器学习·逻辑回归
fengenrong10 小时前
20260429
c++·算法
南宫萧幕10 小时前
Python与Simulink联合仿真:基于DQN的HEV能量管理策略建模与全链路排雷实战
开发语言·人工智能·python·算法·机器学习·matlab·控制
apollowing10 小时前
启发式算法WebApp实验室:从搜索策略到群体智能的能力进阶(优)
算法·启发式算法·web app
Chat_zhanggong34511 小时前
主推NT98336BG作用有哪些?
嵌入式硬件·算法
Run_Teenage11 小时前
算法:线段树
算法
Westward-sun.11 小时前
YOLOv2算法全方位解析:从BatchNorm到聚类先验框的九大改进
算法·yolo·聚类
扶苏xw11 小时前
【离散化算法】
算法