Binary Tree Tilt

25 min · findTilt()

Picture every node as a balance scale. The values hanging below its left and right sides decide how far that scale tips.

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. Given the root of a binary tree, return the sum of every node's tilt.

A few ground rules:

  • An empty subtree has sum 0.
  • A leaf has tilt 0 because both of its subtrees are empty.
  • Negative node values contribute normally to subtree sums.
  • An empty tree returns 0.

Constraints

  • 0 <= node count <= 10_000
  • -1_000 <= node.val <= 1_000
  • 0 <= total tilt <= 2_147_483_647

Hints

Write the definition first

At one node, compute the complete left-subtree sum and right-subtree sum, take their absolute difference, then repeat for both children.

Spot the repeated work

If every ancestor asks for a descendant's subtree sum again, a long one-sided tree gets scanned over and over. What result could each child hand to its parent?

One return value, one side effect

A post-order traversal handles both children before their parent, so a node can receive both child sums. Add their difference to a running total, then return node.val + left_sum + right_sum upward.

Follow-up

Could you produce every node's individual tilt as well as the total in the same pass?

Visible cases

Examples

Example 1

ready
Input
root = [
  1,
  2,
  3
]
Expected
1
Why
the root contributes |2 - 3| = 1

Example 2

ready
Input
root = [
  4,
  2,
  9,
  3,
  5,
  null,
  7
]
Expected
15
Why
adding every node's local imbalance gives 15

Example 3

ready
Input
root = [
  1
]
Expected
0
Why
a leaf has two empty subtrees

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite