# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTilt(self, root: TreeNode) -> int:
self.sum = 0
def helper(root):
"""
the sum of the node values of tree composed of the current root
"""
if not root:
return 0
left = helper(root.left)
right = helper(root.right)
self.sum += abs(left - right)
return left + right + root.val
helper(root)
return self.sum
以图为例进行程序执行的拆解