dsa · easy

Tree Tilt

The **tilt** of a binary-tree node is the absolute difference between the sum of every value in its left subtree and the sum of every value in its right subtree. An empty subtree sums to 0. The tilt of the whole tree is the sum of every node's tilt.

Arguments

Each node is [val, left, right] or None. Return the tree tilt. An empty tree has tilt 0.

Example

root = [1,[2,None,None],[3,None,None]]

Total tilt 1.

[4,[2,[3,None,None],[5,None,None]],[9,None,[7,None,None]]] has node tilts 0, 0, 0, 7, 2 → 9.

Constraints

0 <= number of nodes <= 10^4 -1000 <= node value <= 1000 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
[1,[2,None,None],[3,None,None]]

Expected:
1

Example 2

Input:
[4,[2,[3,None,None],[5,None,None]],[9,None,[7,None,None]]]

Expected:
15

Example 3

Input:
None

Expected:
0

Open in the Dojo editor