1654. Best Average Branch
A mountain trail is modelled as a binary tree; every node is a checkpoint carrying a non-negative integer val that scores its scenery. A branch is any checkpoint together with all checkpoints below it, including a leaf on its own and the entire tree.
The average of a branch is the sum of its scores divided by the number of checkpoints it contains. Given root, return the largest average over all branches as a double. Answers within 1e-6 of the true value are accepted. Compute it in O(n) time and O(n) space by processing every node after its children and combining a (sum, count) pair per node; do not recompute each branch from scratch, and avoid deep recursion on very tall trees.
Example 1
- Input:
- root = [4,10,2,null,null,6,6]
- Output:
- 10
- Explanation:
The subtree rooted at 10 (a lone leaf) has average 10, higher than the whole tree (28/5) and than the 6-6-2 branch.
Example 2
- Input:
- root = [3,3,3]
- Output:
- 3
- Explanation:
Every subtree has average 3.0.
Constraints
1 ≤ number of nodes ≤ 1000
0 ≤ Node.val ≤ 105
How this problem is judged
- Answers
- Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
- Tolerance
0.000001- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)