Skip to content

Latest commit

 

History

History
 
 

1120. Maximum Average Subtree

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given the root of a binary tree, return the maximum average value of a subtree of that tree. Answers within 10-5 of the actual answer will be accepted.

A subtree of a tree is any node of that tree plus all its descendants.

The average value of a tree is the sum of its values, divided by the number of nodes.

 

Example 1:

Input: root = [5,6,1]
Output: 6.00000
Explanation: 
For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4.
For the node with value = 6 we have an average of 6 / 1 = 6.
For the node with value = 1 we have an average of 1 / 1 = 1.
So the answer is 6 which is the maximum.

Example 2:

Input: root = [0,null,1]
Output: 1.00000

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 0 <= Node.val <= 105

Companies:
Amazon

Related Topics:
Tree, Depth-First Search, Binary Tree

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/maximum-average-subtree/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
    double ans = 0;
    pair<int, int> dfs(TreeNode *root) {
        if (!root) return {0,0};
        auto left = dfs(root->left), right = dfs(root->right);
        int sum = left.first + right.first + root->val, cnt = left.second + right.second + 1;
        ans = max(ans, (double)sum / cnt);
        return {sum, cnt};
    }
public:
    double maximumAverageSubtree(TreeNode* root) {
        dfs(root);
        return ans;
    }
};