力扣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);
    }
};
相关推荐
田梓燊11 分钟前
leetcode 56
java·算法·leetcode
仍然.34 分钟前
多线程---阻塞队列收尾和线程池
java·开发语言·算法
_深海凉_34 分钟前
LeetCode热题100-最长公共前缀
算法·leetcode·职场和发展
郝学胜-神的一滴34 分钟前
PyTorch自动微分核心解析:从原理到实战实现权重更新
人工智能·pytorch·python·深度学习·算法·机器学习
会编程的土豆1 小时前
【数据结构与算法】 拓扑排序
数据结构·c++·算法
zth4130211 小时前
SegmentSplay‘s Super STL(v2.2)
开发语言·c++·算法
数据知道1 小时前
claw-code 源码详细分析:Bootstrap Graph——启动阶段图式化之后,排障与扩展为什么会变简单?
前端·算法·ai·bootstrap·claude code·claw code
Kel1 小时前
从Prompt到Response:大模型推理端到端核心链路深度拆解
人工智能·算法·架构
Felven1 小时前
D. Matryoshkas
算法
17(无规则自律)2 小时前
DFS连通域统计:岛屿数量问题及其变形
c++·算法·深度优先