← 返回 snowflake 的题目列表Root Equals Average of All Subtrees
类型:online_judge
Problem: Check Whether the Root Equals the Average of Every Subtree (Variant)
You are given a binary tree root where each node stores an integer value.
For any node x in the tree, define its subtree as the set of nodes consisting of x and all its descendants. Define the average of that subtree as the arithmetic mean of all node values inside the subtree.
Determine whether root.val equals the average of the subtree of every node in the tree.
Return true if for every node x, avg(subtree(x)) == root.val.
Otherwise return false.
Input
A binary tree root.
Node values are in [-10^9, 10^9].
Number of nodes n: 1 <= n <= 2 * 10^5.
Output
A boolean true/false.
Notes
Treat the average as an exact rational number: compare sum(subtree) / size(subtree) to root.val exactly (avoid floating-point tolerance issues).
Sample Tests
Input: [5,5,5] Output: true
Input: [4,8,5,0,1,null,6] Output: false
Input: [1] Output: true
Input: [2,1,3] Output: false
Input: [0,0,0,0,null,null,0] Output: true
Example
Input
[5,5,5]
Output
true