0%

1120. Maximum Average Subtree

O(n) time O(h) space

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(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
double maximumAverageSubtree(TreeNode* root) {
dfs(root);
return res;
}

pair<int, int> dfs(TreeNode *root) {
if (!root) return {0, 0};
auto [ls, lc] = dfs(root->left);
auto [rs, rc] = dfs(root->right);
int s = root->val + ls + rs, c = 1 + lc + rc;
res = max(res, double(s) / c);
return {s, c};
}

double res = 0;
};