-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2265-count-nodes-equal-to-average-of-subtree.js
More file actions
46 lines (41 loc) · 1.27 KB
/
2265-count-nodes-equal-to-average-of-subtree.js
File metadata and controls
46 lines (41 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* 2265. Count Nodes Equal to Average of Subtree
* https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/
* Difficulty: Medium
*
* Given the root of a binary tree, return the number of nodes where the value of the node is
* equal to the average of the values in its subtree.
*
* Note:
* - The average of n elements is the sum of the n elements divided by n and rounded down to
* the nearest integer.
* - A subtree of root is a tree consisting of root and all of its descendants.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var averageOfSubtree = function(root) {
let count = 0;
traverse(root);
return count;
function traverse(node) {
if (!node) return [0, 0];
const [leftSum, leftCount] = traverse(node.left);
const [rightSum, rightCount] = traverse(node.right);
const totalSum = leftSum + rightSum + node.val;
const totalCount = leftCount + rightCount + 1;
if (Math.floor(totalSum / totalCount) === node.val) {
count++;
}
return [totalSum, totalCount];
}
};