[LeetCode] Maximum Average Subtree

1120. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
double avg = 0;
pair<int, int> helper(TreeNode* node) {
if(!node) return {0, 0};
auto [ls, lc] = helper(node->left);
auto [rs, rc] = helper(node->right);
pair<int, int> res {ls + rs + node->val, lc + rc + 1};
avg = max(avg, 1.0 * res.first / res.second);
return res;
}
public:
double maximumAverageSubtree(TreeNode* root) {
helper(root);
return avg;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/13/PS/LeetCode/maximum-average-subtree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.