Please use Laptop/Desktop or any other large screen for the Mock Interview Session.

Count nodes equal to average of subtree and tree iterator



YouTube Video Thumbnail
Link

Watch above sample mock interview video to see how it works.
Login and Buy Premium to Start the Interview



Count Nodes Equal to Subtree Average

Count Nodes Equal to Subtree Average

Problem Statement

Given the root node of a binary tree, find and return the count of nodes where the node's value is exactly equal to the integer average of all values in its subtree.

Note:

  • The average of k numbers is the total sum divided by k, rounded down to the nearest integer.
  • A subtree of a node includes the node itself and all its descendants.

Examples

Example 1:

Input: root = [5,10,7,0,2,null,8]
Output: 4
Explanation:
- Node with value 5: subtree sum is 5+10+7+0+2+8 = 32, count = 6, average = 32 / 6 = 5 (integer division)
- Node with value 7: subtree sum is 7+8 = 15, count = 2, average = 7
- Node with value 0: subtree sum is 0, count = 1, average = 0
- Node with value 8: subtree sum is 8, count = 1, average = 8
Nodes matching their subtree average: 5, 7, 0, 8 (total 4)

Example 2:

Input: root = [3]
Output: 1
Explanation:
Only one node with value 3 whose subtree average is 3 / 1 = 3.

Constraints

  • Number of nodes in the tree: 1 to 1200
  • Node values range from 0 to 1200 inclusive