Problem · Tree
Count Balanced Nodes in a Rooted Tree
Learn this problemProblem statement
You are given a rooted tree represented by an adjacency list subtrees. Node 0 is the root, and subtrees[i] lists the indices of the immediate children of node i.
The size of a subtree is the number of nodes it contains, including the node at its root.
A node is balanced if all of its immediate child subtrees have the same size. A node with zero or one child is balanced.
Return the number of balanced nodes in the tree.
Function
solution(subtrees: int[][]) → intExamples
Example 1
subtrees = [[1,2],[3,4],[5],[],[],[]]return = 5Node 0 has child-subtree sizes 3 and 2, so it is not balanced. Every other node is balanced, giving a total of 5.
Example 2
subtrees = [[1,2,3],[],[],[]]return = 4The root has three child subtrees of size 1. The root and all three leaves are balanced.
Example 3
subtrees = [[1,2],[3],[5,6],[4],[],[],[]]return = 7The two subtrees below the root both have size 3, even though their shapes differ. Every node is balanced.
Constraints
subtreesis non-empty and contains one row for every node.- Node
0is the root. - Every child index is a valid index into
subtrees. - Every node other than node
0appears exactly once among the child lists, node0never appears as a child, and the representation contains no cycle. - The order of indices within a child list does not affect the result.