力扣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);
    }
};
相关推荐
凌肖战19 分钟前
力扣上刷题之C语言实现(数组)
c语言·算法·leetcode
秋夫人1 小时前
B+树(B+TREE)索引
数据结构·算法
梦想科研社1 小时前
【无人机设计与控制】四旋翼无人机俯仰姿态保持模糊PID控制(带说明报告)
开发语言·算法·数学建模·matlab·无人机
Milo_K1 小时前
今日 leetCode 15.三数之和
算法·leetcode
Darling_001 小时前
LeetCode_sql_day28(1767.寻找没有被执行的任务对)
sql·算法·leetcode
AlexMercer10121 小时前
【C++】二、数据类型 (同C)
c语言·开发语言·数据结构·c++·笔记·算法
Greyplayground1 小时前
【算法基础实验】图论-BellmanFord最短路径
算法·图论·最短路径
蓑 羽2 小时前
力扣438 找到字符串中所有字母异位词 Java版本
java·算法·leetcode
源代码:趴菜2 小时前
LeetCode63:不同路径II
算法·leetcode·职场和发展
严格格2 小时前
三范式,面试重点
数据库·面试·职场和发展