Problem 440766 · medium · Level 04 Non-Linear Data Structures

How Lopsided Is the Mobile?

binary trees · postorder traversal · subtree sums

A hanging mobile is built as a binary tree: every node is a weight, and from it hang a left arm and a right arm. A node's tilt says how far its arms are out of balance: the absolute difference between the total of all values hanging on its left side and the total on its right side (an empty side weighs 0). Given the root, return the sum of the tilts of every node. An empty mobile has total tilt 0.

Examples

    6
   / \
  3   8
 / \
2   5

Input:  root = build_tree([6, 3, 8, 2, 5])
Output: 5
Explanation: tilt(2) = tilt(5) = tilt(8) = 0, tilt(3) = |2 - 5| = 3, tilt(6) = |10 - 8| = 2.
Input:  root = build_tree([1, None, 2, None, 3])
Output: 8
Explanation: tilt(3) = 0, tilt(2) = |0 - 3| = 3, tilt(1) = |0 - 5| = 5.

Constraints

  • 0 <= number of nodes <= 2000
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n) time.

Goals

  • Compute subtree sums bottom-up
  • Accumulate a side result while returning another
  • Handle negative values with abs
Starting Python…