力扣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);
    }
};
相关推荐
赵鑫亿1 小时前
7.DP算法
算法·dp
iqay1 小时前
【C语言】填空题/程序填空题1
c语言·开发语言·数据结构·c++·算法·c#
还有糕手1 小时前
算法【有依赖的背包】
算法·动态规划
pursuit_csdn2 小时前
力扣 347. 前 K 个高频元素
算法·leetcode
wen__xvn2 小时前
每日一题洛谷B3865 [GESP202309 二级] 小杨的 X 字矩阵c++
c++·算法·矩阵
makabaka_T_T2 小时前
25寒假算法刷题 | Day1 | LeetCode 240. 搜索二维矩阵 II,148. 排序链表
数据结构·c++·算法·leetcode·链表·矩阵
辞半夏丶北笙3 小时前
最近最少使用算法(LRU最近最少使用)缓存替换算法
java·算法·缓存
BingLin-Liu3 小时前
蓝桥杯备考:六大排序算法
算法·排序算法
南玖yy3 小时前
C语言:数组的介绍与使用
c语言·开发语言·算法
小菜鸟博士3 小时前
手撕Vision Transformer -- Day1 -- 基础原理
人工智能·深度学习·学习·算法·面试