力扣637. 二叉树的层平均值

深度优先遍历

  • 思路:
    • 使用深度优先搜索计算二叉树的层平均值,维护两个数组用于统计各层节点和、各层节点个数;
    • 递归统计时,需要传入当前统计深度;
cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        auto counts = std::vector<int>();
        auto sums = std::vector<double>();

        dfs(root, 0, counts, sums);

        int size = sums.size();
        auto averages = std::vector<double>();
        for (int i = 0; i < size; ++i) {
            averages.push_back(sums[i] / counts[i]);
        }

        return averages;
    }

    void dfs(TreeNode* root, int depth, std::vector<int>& counts, std::vector<double>& sums) {
        if (root == nullptr) {
            return;
        }

        if (depth < sums.size()) {
            sums[depth] += root->val;
            counts[depth] += 1;
        } else {
            sums.push_back(1.0 * root->val);
            counts.push_back(1);
        }
        
        dfs(root->left, depth + 1, counts, sums);
        dfs(root->right, depth + 1, counts, sums);
    }
};
相关推荐
浮灯Foden19 分钟前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
西工程小巴1 小时前
实践笔记-VSCode与IDE同步问题解决指南;程序总是进入中断服务程序。
c语言·算法·嵌入式
Tina学编程1 小时前
48Days-Day19 | ISBN号,kotori和迷宫,矩阵最长递增路径
java·算法
Moonbit1 小时前
MoonBit Perals Vol.06: MoonBit 与 LLVM 共舞 (上):编译前端实现
后端·算法·编程语言
执子手 吹散苍茫茫烟波2 小时前
leetcode415. 字符串相加
java·leetcode·字符串
百度Geek说3 小时前
第一!百度智能云领跑视觉大模型赛道
算法
big_eleven3 小时前
轻松掌握数据结构:二叉树
后端·算法·面试
big_eleven3 小时前
轻松掌握数据结构:二叉查找树
后端·算法·面试
CoovallyAIHub3 小时前
农田扫描提速37%!基于检测置信度的无人机“智能抽查”路径规划,Coovally一键加速模型落地
深度学习·算法·计算机视觉
执子手 吹散苍茫茫烟波3 小时前
LCR 076. 数组中的第 K 个最大元素
leetcode·排序算法