Binary Tree Tilt

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

30:00

Binary Tree Tilt
easy
Free written solution
Topics
Companies

Given the root of a binary tree, return the sum of every node's tilt.

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 has sum 0, so a leaf has tilt 0.

Example 1:
Input: {"root":[1,2,3]}
Output: 1
Constraints:
  • The number of nodes in the tree is in the range [0,104][0, 10^4].

  • −1000≤Node.val≤1000-1000 \leq \text{Node.val} \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,2,3]}

total starts at 0. Each call will return its subtree sum and add its own tilt to total.

total tilt

0

nothing added yet

123
current call
call stack
returned
Σ subtree sum
+tilt
Variables
VariableValue
total0
DepthFunction Call
Stack empty
0/7