其他分享
首页 > 其他分享> > [LeetCode] 1120. Maximum Average Subtree

[LeetCode] 1120. Maximum Average Subtree

作者:互联网

Given the root of a binary tree, find the maximum average value of any subtree of that tree.

(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: [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.

Note:

  1. The number of nodes in the tree is between 1 and 5000.
  2. Each node will have a value between 0 and 100000.
  3. Answers will be accepted as correct if they are within 10^-5 of the correct answer.

子树的最大平均值。

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-average-subtree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

既然是计算子树的信息,那么思路应该是后序遍历。这里的helper函数有一些特别,需要记录两个信息,一个是所有子树值的和,一个是子树节点的个数。这里我用一个长度为2的数组记录这两个信息。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     double res = 0;
18 
19     public double maximumAverageSubtree(TreeNode root) {
20         if (root == null) {
21             return res;
22         }
23         helper(root);
24         return res;
25     }
26 
27     private int[] helper(TreeNode root) {
28         int[] arr = new int[2];
29         if (root == null) {
30             return arr;
31         }
32         int[] left = helper(root.left);
33         int[] right = helper(root.right);
34         //设置当前树的元素和
35         arr[0] = left[0] + right[0] + root.val;
36         //设置节点个数
37         arr[1] = left[1] + right[1] + 1;
38         //更新平均值
39         res = Math.max(res, (double) arr[0] / arr[1]);
40         return arr;
41     }
42 }

 

LeetCode 题目总结

标签:right,TreeNode,val,1120,Average,Subtree,int,root,left
来源: https://www.cnblogs.com/cnoodle/p/14414330.html