Average of Levels in Binary Tree

Given the root of a binary tree, return the average value of the nodes on each level, as an array ordered from the top level down. Answers within 10^-5 of the actual value are accepted.

30:00

Average of Levels in Binary Tree
easy
Free written solution
Topics
Companies

Given the root of a binary tree, return the average value of the nodes on each level, as an array ordered from the top level down. Answers within 10^-5 of the actual value are accepted.

Example 1:
Input: {"root":[3,9,20,null,null,15,7]}
Output: [3,14.5,11]
Constraints:
  • The number of nodes in the tree is in the range [1,104][1, 10^4].

  • −231≤Node.val≤231−1-2^{31} \leq \text{Node.val} \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[3,9,20,null,null,15,7]}

Put the root 3 in the queue. The queue will always hold exactly one level when a pass begins.

L0L1L23920157

queue (front first)

3

No level summed yet.

result =

[

]

waiting in queue
summed this level
level averaged
Variables
VariableValue
size0
level_sum0
nodenull
queue[3]
result[]
DepthFunction Call
Stack empty
0/17