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.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.
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.
root=tree_node([]) → 0
An empty tree has nothing to tip over, so the answer is 0.
Node.val ≤ 1000root=tree_node([5, 6, 1])
5
Run checks the first 3 tests in your browser. Submit checks all 92 tests on the server, hidden ones included.