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

Total Tilt

binary trees · postorder traversal · subtree sums

A mobile hangs from every node of a binary tree. The tilt of a node is the absolute difference between the sum of all values in its left subtree and the sum of all values in its right subtree (a missing subtree sums to 0). Given the root, return the sum of the tilts of all nodes. The empty tree has total tilt 0.

Examples

    4
   / \
  2   9
 / \
1   3

Input:  root = build_tree([4, 2, 9, 1, 3])
Output: 5
Explanation: tilt(1) = tilt(3) = tilt(9) = 0, tilt(2) = |1 - 3| = 2, tilt(4) = |6 - 9| = 3.
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…