📜  给定二叉树中子树值的最大平均值

📅  最后修改于: 2021-04-29 16:46:34             🧑  作者: Mango

给定一个由N个节点组成的二叉树,该任务将查找任何子树的节点的值的最大平均值。

例子:

方法:给定的问题类似于在树中找到最大的子树总和的问题。这个想法是使用DFS遍历技术。请按照以下步骤解决问题:

  • 初始化一个变量, ans0,用于存储结果。
  • 为DFS遍历定义一个函数maxAverage()
    • 初始化两个变量, sum用于存储其子树的总和,而count用于存储其子树中的节点数(以0表示)
    • 遍历当前节点的子节点,并为其子节点调用maxAverage() ,然后将总和增加子节点子树的总和,并以该子节点中的总节点数进行计数
    • 根据当前节点的值增加总和 并以1计数
    • ans的最大值并求和/计数,然后将其存储在ans中
    • 最后,返回{sum,count}对
  • 将获得的最大平均值打印为ans
C++
// C++ program for the above approach
#include 
using namespace std;
 
struct TreeNode
{
    int val;
     
    vector children;
     
    TreeNode(int v)
    {
        val = v;
    }
};
 
// Stores the result
double ans = 0.0;
 
// Function for finding maximum
// subtree average
vector MaxAverage(TreeNode* root)
{
     
    // Checks if current node is not
    // NULL and doesn't have any children
    if (root != NULL && root->children.size() == 0)
    {
        ans = max(ans, (root->val) * (1.0));
        return {root->val, 1};
    }
 
    // Stores sum of its subtree in index 0
    // and count number of nodes in index 1
    vector childResult (2);
 
    // Traverse all children of the current node
    for(TreeNode *child : root->children)
    {
         
        // Recursively calculate max average
        // of subtrees among its children
        vector childTotal = MaxAverage(child);
 
        // Increment sum by sum
        // of its child's subtree
        childResult[0]     = childResult[0] + childTotal[0];
 
        // Increment number of nodes
        // by its child's node
        childResult[1] = childResult[1] + childTotal[1];
    }
 
    // Increment sum by current node's value
    int sum = childResult[0] + root->val;
 
    // Increment number of
    // nodes by one
    int count = childResult[1] + 1;
 
    // Take maximum of ans and
    // current node's average
    ans = max(ans, sum / count * 1.0);
 
    // Finally return pair of {sum, count}
    return{sum, count};
}
 
// Driver Code
int main()
{
     
    // Given tree
    TreeNode *root = new TreeNode(20);
    TreeNode *left = new TreeNode(12);
    TreeNode *right = new TreeNode(18);
     
    root->children.push_back(left);
    root->children.push_back(right);
     
    left->children.push_back(new TreeNode(11));
    left->children.push_back(new TreeNode(3));
    right->children.push_back(new TreeNode(15));
    right->children.push_back(new TreeNode(8));
 
    // Function call
    MaxAverage(root);
 
    // Print answer
    printf("%0.1f\n", ans);
}
 
// This code is contributed by mohit kumar 29


Java
// Java program for the above approach
 
import java.util.*;
 
// Structure of the Tree node
class TreeNode {
    public int val;
    public List children;
 
    public TreeNode(int v)
    {
        val = v;
        children = new ArrayList();
    }
}
 
class GFG {
 
    // Stores the result
    static double ans = 0.0;
 
    // Function for finding maximum
    // subtree average
    public static double[] MaxAverage(
        TreeNode root)
    {
 
        // Checks if current node is not
        // null and doesn't have any children
        if (root.children != null
            && root.children.size() == 0) {
            ans = Math.max(ans, root.val);
            return new double[] { root.val, 1 };
        }
 
        // Stores sum of its subtree in index 0
        // and count number of nodes in index 1
        double[] childResult = new double[2];
 
        // Traverse all children of the current node
        for (TreeNode child : root.children) {
 
            // Recursively calculate max average
            // of subtrees among its children
            double[] childTotal
                = MaxAverage(child);
 
            // Increment sum by sum
            // of its child's subtree
            childResult[0]
                = childResult[0] + childTotal[0];
 
            // Increment number of nodes
            // by its child's node
            childResult[1]
                = childResult[1] + childTotal[1];
        }
 
        // Increment sum by current node's value
        double sum = childResult[0] + root.val;
 
        // Increment number of
        // nodes by one
        double count = childResult[1] + 1;
 
        // Take maximum of ans and
        // current node's average
        ans = Math.max(ans, sum / count);
 
        // Finally return pair of {sum, count}
        return new double[] { sum, count };
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given tree
        TreeNode root = new TreeNode(20);
        TreeNode left = new TreeNode(12);
        TreeNode right = new TreeNode(18);
        root.children.add(left);
        root.children.add(right);
        left.children.add(new TreeNode(11));
        left.children.add(new TreeNode(3));
        right.children.add(new TreeNode(15));
        right.children.add(new TreeNode(8));
 
        // Function call
        MaxAverage(root);
 
        // Print answer
        System.out.println(ans);
    }
}


Python3
# Python3 program for the above approach
 
# Stores the result
ans = 0.0
 
class TreeNode:
     
    def __init__ (self, val):
       
        self.val = val
        self.children = []
 
# Function for finding maximum
# subtree average
def MaxAverage(root):
     
    global ans
     
    # Checks if current node is not
    # None and doesn't have any children
    if (root != None and len(root.children) == 0):
        ans = max(ans, (root.val))
        return [root.val, 1]
 
    # Stores sum of its subtree in index 0
    # and count number of nodes in index 1
    childResult = [0 for i in range(2)]
 
    # Traverse all children of the current node
    for child in root.children:
         
        # Recursively calculate max average
        # of subtrees among its children
        childTotal = MaxAverage(child)
 
        # Increment sum by sum
        # of its child's subtree
        childResult[0] = childResult[0] + childTotal[0]
 
        # Increment number of nodes
        # by its child's node
        childResult[1] = childResult[1] + childTotal[1]
 
    # Increment sum by current node's value
    sum = childResult[0] + root.val
 
    # Increment number of
    # nodes by one
    count = childResult[1] + 1
 
    # Take maximum of ans and
    # current node's average
    ans = max(ans, sum / count)
 
    # Finally return pair of {sum, count}
    return [sum, count]
 
# Driver Code
if __name__ == '__main__':
     
    # Given tree
    root =  TreeNode(20)
    left =  TreeNode(12)
    right =  TreeNode(18)
     
    root.children.append(left)
    root.children.append(right)
     
    left.children.append(TreeNode(11))
    left.children.append(TreeNode(3))
    right.children.append(TreeNode(15))
    right.children.append(TreeNode(8))
 
    # Function call
    MaxAverage(root)
 
    # Print answer
    print(ans * 1.0)
 
# This code is contributed by ipg2016107


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
using System.Globalization;
public class TreeNode
{
  public int val;
  public List children;
 
  public TreeNode(int v)
  {
    val = v;
    children = new List();
  }
}
 
public class GFG
{
 
  // Stores the result
  static double ans = 0.0;
 
  // Function for finding maximum
  // subtree average
  public static double[] MaxAverage( TreeNode root)
  {
 
    // Checks if current node is not
    // null and doesn't have any children
    if (root.children != null
        && root.children.Count == 0)
    {
      ans = Math.Max(ans, root.val);
      return new double[] { root.val, 1 };
    }
 
    // Stores sum of its subtree in index 0
    // and count number of nodes in index 1
    double[] childResult = new double[2];
 
    // Traverse all children of the current node
    foreach (TreeNode child in root.children)
    {
 
      // Recursively calculate max average
      // of subtrees among its children
      double[] childTotal
        = MaxAverage(child);
 
      // Increment sum by sum
      // of its child's subtree
      childResult[0]
        = childResult[0] + childTotal[0];
 
      // Increment number of nodes
      // by its child's node
      childResult[1]
        = childResult[1] + childTotal[1];
    }
 
    // Increment sum by current node's value
    double sum = childResult[0] + root.val;
 
    // Increment number of
    // nodes by one
    double count = childResult[1] + 1;
 
    // Take maximum of ans and
    // current node's average
    ans = Math.Max(ans, sum / count);
 
    // Finally return pair of {sum, count}
    return new double[] { sum, count };
  }
 
  // Driver code
  static public void Main ()
  {
    // Given tree
    TreeNode root = new TreeNode(20);
    TreeNode left = new TreeNode(12);
    TreeNode right = new TreeNode(18);
    root.children.Add(left);
    root.children.Add(right);
    left.children.Add(new TreeNode(11));
    left.children.Add(new TreeNode(3));
    right.children.Add(new TreeNode(15));
    right.children.Add(new TreeNode(8));
 
    // Function call
    MaxAverage(root);
 
    // Print answer
    NumberFormatInfo setPrecision = new NumberFormatInfo();
 
    setPrecision.NumberDecimalDigits = 1;
 
    Console.WriteLine(ans.ToString("N", setPrecision));
  }
}
 
// This code is contributed by rag2127


输出:
15.0

时间复杂度: O(N)
辅助空间: O(N)