Average Binary-Tree Values at Each Depth

Quick Overview

Average Binary-Tree Values at Each Depth. Return the average node value at every depth of the binary tree, starting with the root level.

Average Binary-Tree Values at Each Depth

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Return the average node value at every depth of the binary tree, starting with the root level. TreeNode exposes val,left,right. Answers within 10^-5 of the mathematical averages are accepted. ```cpp class Solution { public: vector<double> averageOfLevels(TreeNode* root); }; ``` ### Examples **Example 1:** ```text root = [4,2,9,1,7] Output: [4.0,5.5,4.0] Explanation: Level sums are 4,11,8 with counts 1,2,2. ``` **Example 2:** ```text root = [-3,-5,1] Output: [-3.0,-2.0] Explanation: The second level averages (-5+1)/2. ``` ### Constraints - Tree size: 1..10000 nodes. Each node stores a signed-32-bit value, from -2147483648 to 2147483647. ### Clarifying Questions Compute arithmetic means per level and preserve the stated numeric acceptance tolerance. ```hint Read the boundary condition How can the queue size identify the boundary between two levels? ``` ### Contract considerations Compute arithmetic means per level and preserve the stated numeric acceptance tolerance.

Overview: Average Binary-Tree Values at Each Depth. Return the average node value at every depth of the binary tree, starting with the root level.

Amazon logo
Amazon
Jul 4, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return the average node value at every depth of the binary tree, starting with the root level. TreeNode exposes val,left,right. Answers within 10^-5 of the mathematical averages are accepted.

class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root);
};

Examples

Example 1:

root = [4,2,9,1,7]
Output: [4.0,5.5,4.0]
Explanation: Level sums are 4,11,8 with counts 1,2,2.

Example 2:

root = [-3,-5,1]
Output: [-3.0,-2.0]
Explanation: The second level averages (-5+1)/2.

Constraints

  • Tree size: 1..10000 nodes. Each node stores a signed-32-bit value, from -2147483648 to 2147483647.

Clarifying Questions Guidance

Compute arithmetic means per level and preserve the stated numeric acceptance tolerance.

Contract considerations

Compute arithmetic means per level and preserve the stated numeric acceptance tolerance.