Loading content...
You are given the root of a binary tree. Your task is to compute the cumulative balance metric of the entire tree.
The balance metric of a single node is defined as the absolute difference between:
If a node has no left child, the left subtree sum is considered to be 0. Similarly, if a node has no right child, the right subtree sum is considered to be 0.
The cumulative balance metric of the tree is the sum of the balance metrics of all individual nodes in the tree.
Return this cumulative balance metric as an integer.
root = [1,2,3]1We analyze each node's balance metric: • Node 2 (leaf): |0 - 0| = 0 (no children, both subtree sums are 0) • Node 3 (leaf): |0 - 0| = 0 (no children, both subtree sums are 0) • Node 1 (root): |2 - 3| = 1 (left subtree sum = 2, right subtree sum = 3) Total cumulative balance metric: 0 + 0 + 1 = 1
root = [4,2,9,3,5,null,7]15Analyzing each node from leaves to root: • Node 3: |0 - 0| = 0 (leaf node) • Node 5: |0 - 0| = 0 (leaf node) • Node 7: |0 - 0| = 0 (leaf node) • Node 2: |3 - 5| = 2 (left child sum = 3, right child sum = 5) • Node 9: |0 - 7| = 7 (no left child, right child sum = 7) • Node 4: |(3+5+2) - (9+7)| = |10 - 16| = 6 (left subtree sum = 10, right subtree sum = 16) Total: 0 + 0 + 0 + 2 + 7 + 6 = 15
root = [21,7,14,1,1,2,2,3,3]9This tree has multiple levels. Computing balance metrics for all nodes and summing them yields a cumulative balance metric of 9.
Constraints