力扣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);
    }
};
相关推荐
文丑颜不良啊31 分钟前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊1 小时前
LeetCode2001~2020题目解析
java·leetcode
加宝的起点雷达3 小时前
40 条候选里 38 条来自同一个源,主卡整屏重样
人工智能·算法·创业
秋天的怀念_David3 小时前
算法一千零一夜 · 第二十六夜 协议的母语
java·spring boot·算法
文丑颜不良啊4 小时前
LeetCode2021~2040题目解析
java·leetcode
Yuzhiyuxia5 小时前
【AI Agent面试系列】上下文管理1
人工智能·面试·职场和发展
闻缺陷则喜何志丹6 小时前
【C++特性】四种类型转
c++·算法·类型转换
喵本喵叁肆6 小时前
用 Boosting 把弱隐私算法炼成强隐私算法(英文原题:Boosting and Differential Privacy (FOCS 2010))
算法·集成学习·boosting