Skip to the code
cf.
+10 XP

#324 Average Load per Tier

easy

A CDN dashboard shows a cache tree: the origin server at the top, then edge servers below it, then smaller caches below those. Each node holds its current load as a number.

Write averageByTier(root) that returns the average load of each level, from the top level down. An empty tree returns []. Answers within 1e-5 of the expected value are accepted.

Example 1

Input: root = [4,2,9,1,3]
Output: [4,5.5,2]

Level 1 is (2 + 9) / 2 = 5.5, and level 2 is (1 + 3) / 2 = 2.

Example 2

Input: root = [10,null,20,null,30]
Output: [10,20,30]

Each level has a single server.

Constraints

  • 0 <= number of servers <= 10000
  • 0 <= load <= 10^6

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).