Ctrl K

Total Tree Imbalance

Easy
You are given the root of a binary tree with an integer in every node. The *imbalance* 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 counts as 0, so a leaf has an imbalance of 0. Return the sum of the imbalances of all nodes. For an empty tree, the answer is 0.
Example 1
root=tree_node([5, 6, 1]) → 5

Leaves 6 and 1 have imbalance 0. The root has 6 on the left and 1 on the right, so |6 − 1| = 5. The total is 5.

Example 2
root=tree_node([2, 4, None, 3, -1]) → 10

Node 4 has 3 on the left and −1 on the right: |3 − (−1)| = 4. The root has 4 + 3 − 1 = 6 on the left and nothing on the right: 6. The total is 4 + 6 = 10.

Example 3
root=tree_node([]) → 0

An empty tree has nothing to tip over, so the answer is 0.

Constraints
  • 0 ≤ number of nodes ≤ 10⁵
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLeft, Node, Right EasyIdentical Trees EasyMirror-Image Tree EasyTree Height EasyEvenly Grown Tree Easy
loading Python…
Input
root=tree_node([5, 6, 1])
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 92 tests on the server, hidden ones included.