力扣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);
    }
};
相关推荐
Freshman小白6 分钟前
python算法打包为docker镜像(边缘端api服务)
python·算法·docker
mit6.82426 分钟前
[VT-Refine] Simulation | Fine-Tuning | docker/run.sh
算法
朴shu32 分钟前
Delta数据结构:深入剖析高效数据同步的奥秘
javascript·算法·架构
mit6.8241 小时前
博弈dp|凸包|math分类
算法
Shinom1ya_1 小时前
算法 day 41
数据结构·算法·leetcode
hetao17338372 小时前
2025-10-30 ZYZOJ Star(斯达)模拟赛 hetao1733837的record
c++·算法
无敌最俊朗@2 小时前
C++ 值类别与移动语义详解(精简版)
java·数据结构·算法
lingran__2 小时前
算法沉淀第十一天(序列异或)
c++·算法
一匹电信狗3 小时前
【C++】红黑树详解(2w字详解)
服务器·c++·算法·leetcode·小程序·stl·visual studio
天才测试猿3 小时前
Selenium三大等待详解
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例