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. A subtree of root
is a tree consisting of root
and all of its descendants. The average of n
elements is the sum of the n
elements divided by n
and rounded down to the nearest integer.
For example:
Consider the binary tree: [4,8,5,0,1,null,6]
Therefore, the expected output is 5.
Another example:
Consider the binary tree: [1]
Therefore, the expected output is 1.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def averageOfSubtree(self, root: TreeNode) -> int:
self.count = 0
def dfs(node):
if not node:
return 0, 0 # (sum, count)
left_sum, left_count = dfs(node.left)
right_sum, right_count = dfs(node.right)
total_sum = node.val + left_sum + right_sum
total_count = 1 + left_count + right_count
if node.val == total_sum // total_count:
self.count += 1
return total_sum, total_count
dfs(root)
return self.count
The averageOfSubtree
function calculates the number of nodes in a binary tree where the node's value is equal to the average of its subtree. The approach uses a depth-first search (DFS) traversal.
val
, left
, and right
pointers.dfs
function recursively traverses the binary tree.
None
, it returns (0, 0)
indicating a sum of 0 and a count of 0.dfs
on the left and right subtrees.self.count
variable is incremented.averageOfSubtree
function initializes a self.count
variable to 0. It calls the dfs
function starting from the root node and returns the final self.count
.For the input root = [4,8,5,0,1,null,6]
, the code will:
None
, the function correctly returns 0 because dfs
will not be called.Time Complexity: O(N), where N is the number of nodes in the binary tree. The DFS traversal visits each node once.
Space Complexity: O(H), where H is the height of the binary tree. This is due to the recursive call stack during the DFS traversal. In the worst-case scenario (skewed tree), H can be equal to N, resulting in O(N) space complexity. In the best-case scenario (balanced tree), H would be log(N), resulting in O(log(N)) space complexity.