774. Maximum Average Subtree

Given the root of a binary tree, the task is to find the maximum average value among all the subtrees of that tree.

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

The average of a subtree is calculated as the sum of all its node values divided by the number of nodes in that subtree.

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

Explanation: The given tree has two nodes: 0 as the root and 1 as its right child. The subtree {1} has the highest average of 1.00000, which is greater than the average of the entire tree (0+1)/2 = 0.5.

Now Your Turn!

Pick the correct output for the given input

Input: root = [3,4,5]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

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

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
 
class Solution {
public:
double maximumAverageSubtree(TreeNode* root) {
//Your Code Goes Here
}
};
Test Case

Input:

Root