VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-average-of-subtree-values-in-a-given-binary-tree/

⇱ Maximum average of subtree values in a given Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum average of subtree values in a given Binary Tree

Last Updated : 15 Jul, 2025

Given a Binary Tree consisting of N nodes, the task to find the maximum average of values of nodes of any subtree.

Examples: 

Input:                   5
                            /   \
                          3     8 
Output: 8
Explanation:
Average of values of subtree of node 5 = (5 + 3 + 8) / 3 = 5.33
Average of values of subtree of node 3 = 3 / 1 = 3
Average of values of subtree of node 8 = 8 / 1 = 8.

Input:                 20
                        /       \
                    12        18
                   /   \       /  \
                 11    3    15  8 
Output: 15
Explanation: Average of values of subtree of node 15 is the maximum.

Approach: The given problem is similar to that of finding the largest subtree sum in a tree. The idea is to use DFS traversal technique. Follow the steps below to solve the problem:

  • Initialize a variable, ans with 0 for storing the result.
  • Define a function maxAverage() for DFS traversal.
    • Initialize two variables, sum to store the sum of its subtree and count to store the number of nodes in its subtree, with 0.
    • Traverse over the child nodes of the current node and call the maxAverage() for its children node, and increment sum by sum of child's node subtree and count by total nodes in the child's node
    • Increment sum by current node's value and count by 1.
    • Take the maximum of the ans and sum/count and store it in ans.
    • Finally, return pair of the {sum, count}.
  • Print the maximum average obtained as ans.

Output: 
15.0

 

Time Complexity: O(N)
Auxiliary Space: O(N) 

Comment
Article Tags: