力扣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);
    }
};
相关推荐
纪元A梦1 小时前
贪心算法应用:配送路径优化问题详解
算法·贪心算法
C_player_0011 小时前
——贪心算法——
c++·算法·贪心算法
kyle~3 小时前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法
Boop_wu3 小时前
[数据结构] 队列 (Queue)
java·jvm·算法
Nan_Shu_6143 小时前
Web前端面试题(1)
前端·面试·职场和发展
hn小菜鸡3 小时前
LeetCode 3643.垂直翻转子矩阵
算法·leetcode·矩阵
ゞ 正在缓冲99%…4 小时前
leetcode101.对称二叉树
算法
YuTaoShao5 小时前
【LeetCode 每日一题】3000. 对角线最长的矩形的面积
算法·leetcode·职场和发展
2zcode5 小时前
基于Matlab可见光通信系统中OOK调制的误码率性能建模与分析
算法·matlab·php
纵有疾風起5 小时前
数据结构中的排序秘籍:从基础到进阶的全面解析
c语言·数据结构·算法·排序算法