手撕算法-二叉树的层平均值

描述

分析

二叉树的层序遍历。

层序遍历需要用到队列。

代码

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    List<Double> res = new ArrayList<>();

    public List<Double> averageOfLevels(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        bfs(queue);
        return res;
    }

    public void bfs(Queue<TreeNode> queue) {
        int len = queue.size(); // 获取这一层的节点数
        if(len == 0) return;

        long sum = 0; // 注意,放置int类型溢出,使用long型
        for (int i = 0; i < len; i++) {
            TreeNode node = queue.poll(); // 取出
            sum += node.val;
            if (node.left != null) {
                queue.offer(node.left); // 左节点放入队列 
            }
            if (node.right != null) {
                queue.offer(node.right); // 右节点放入队列
            }
        }

        res.add((double) sum / (double) len);

        bfs(queue);
    }
}

面试公司

相关推荐
朝朝辞暮i1 小时前
C++ 第 23 课:class —— 开始真正进入面向对象
开发语言·c++·算法
Evand J2 小时前
【MATLAB例程】三维RRT+APF避障路径规划与到达角(AOA)定位算法|三维路径优化与定位仿真例程
算法·matlab·路径规划·代码·定位·rrt·aoa
weixin_307779133 小时前
有限产能智能排产与动态重排智能体:从需求解构到技术实现
开发语言·人工智能·算法·架构
朝朝辞暮i3 小时前
C++ 第 27 课:智能指针 shared_ptr
开发语言·c++·算法
朝朝辞暮i4 小时前
C++ 第 29 课:回调函数 Callback
开发语言·c++·算法
Godspeed Zhao4 小时前
现代智能雷达技术14——算法(0)
线性代数·算法·雷达
可乐ea4 小时前
Agent 模型分级升级路由:用置信度阈值把贵模型省下来
人工智能·算法·机器学习·结构化输出·置信度路由·模型升级路由·大模型成本优化
Navigator_Z5 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
Godspeed Zhao5 小时前
现代智能雷达技术18——算法(4)
算法
CHEEVEN_QY5 小时前
液冷板热阻计算与流阻优化的实战方法
人工智能·算法·机器学习