Ctrl K

Subtree With the Best Average

Medium
You are given the root of a binary tree. The subtree of a node is that node together with all of its descendants, and its average is the sum of its values divided by its number of nodes. Find the largest average among the subtrees of all nodes in the tree. Answers within 10⁻⁵ of the exact value are accepted.
Example 1
root=tree_node([5, 1, 10, None, None, 2, 3]) → 5.0

Node 10 has the subtree {10, 2, 3} with average (10 + 2 + 3) / 3 = 5. The whole tree averages 21 / 5 = 4.2, and the leaves 1, 2 and 3 average their own values. The best is 5.0.

Example 2
root=tree_node([0, None, 7, 4]) → 5.5

Leaf 4 gives 4, the subtree of 7 gives (7 + 4) / 2 = 5.5, and the whole tree gives 11 / 3 ≈ 3.67. The answer is 5.5.

Example 3
root=tree_node([4]) → 4.0
Constraints
  • The tree has between 1 and 10⁵ nodes
  • 0 ≤ node value ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumDigit Branch Totals Medium
loading Python…
Input
root=tree_node([5, 1, 10, None, None, 2, 3])
Expected
5.0

Run checks the first 3 tests in your browser. Submit checks all 89 tests on the server, hidden ones included.