leetcode 1120. 子树的最大平均值(C++)

给你一棵二叉树的根节点 root,找出这棵树的 每一棵 子树的 平均值 中的 最大 值。

子树是树中的任意节点和它的所有后代构成的集合。

树的平均值是树中节点值的总和除以节点数。

 

示例:

输入:[5,6,1]
输出:6.00000
解释: 
以 value = 5 的节点作为子树的根节点,得到的平均值为 (5 + 6 + 1) / 3 = 4。
以 value = 6 的节点作为子树的根节点,得到的平均值为 6 / 1 = 6。
以 value = 1 的节点作为子树的根节点,得到的平均值为 1 / 1 = 1。
所以答案取最大值 6。

 

提示:

  1. 树中的节点数介于 1 到 5000之间。
  2. 每个节点的值介于 0 到 100000 之间。
  3. 如果结果与标准答案的误差不超过 10^-5,那么该结果将被视为正确答案。

C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    double res=0;
    
    pair<int,int> dfs(TreeNode* root)
    {
        int sum=root->val;
        int num=1;
        if(root->left)
        {
            auto it=dfs(root->left);
            sum+=it.first;
            num+=it.second;
        }
        if(root->right)
        {
            auto it=dfs(root->right);
            sum+=it.first;
            num+=it.second;            
        }
        double ave=(double)sum/(double)num;
        res=max(res,ave);
        return make_pair(sum,num);
    }
    
    double maximumAverageSubtree(TreeNode* root) 
    {
        res=0;
        dfs(root);
        return res;
    }
};

法2:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void dfs(TreeNode* root, int* res, int* num)
    {
        if(root)
        {
            *res+=root->val;
            *num+=1;
            dfs(root->left,res,num);
            dfs(root->right,res,num);
        }
    }
    
    double maximumAverageSubtree(TreeNode* root) 
    {
        if(root)
        {
            int tmp=0;
            int* res=&tmp;
            int count=0;
            int* num=&count;
            dfs(root,res,num);   
            double ans=(double)tmp/(double)count;
            double left=maximumAverageSubtree(root->left);
            double right=maximumAverageSubtree(root->right);
            return max(max(left,right),ans);
        }
        else
        {
            return 0;
        }
    }
};

 

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值