LeetCode 1120. Maximum Average Subtree
原题链接在这里:https://leetcode.com/problems/maximum-average-subtree/
题目:
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
题解:
For each dfs, state is the current node. return value is array containing subtree sum and subtree node count.
Before return, update the global maximum value.
Time Complexity: O(n). n is the number of nodes.
Space: O(logn). stack space.
AC 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.0; 18 public double maximumAverageSubtree(TreeNode root) { 19 if(root == null){ 20 return res; 21 } 22 23 dfs(root); 24 return res; 25 } 26 27 private int[] dfs(TreeNode root){ 28 if(root == null){ 29 return new int[]{0, 0}; 30 } 31 32 int [] l = dfs(root.left); 33 int [] r = dfs(root.right); 34 int sum = l[0] + r[0] + root.val; 35 int count = l[1] + r[1] + 1; 36 res = Math.max(res, 1.0 * sum / count); 37 return new int[]{sum, count}; 38 } 39 }