Skip to main content

563. Binary Tree Tilt

Python

class Solution:
def __init__(self):
self.total_tilt = 0

def findTilt(self, root: Optional[TreeNode]) -> int:
self._travel(0, root)
return self.total_tilt

def _travel(self, total: int, node) -> tuple:
if not node:
return 0

left_total = self._travel(0, node.left)
right_total = self._travel(0, node.right)

self.total_tilt += abs(left_total - right_total)

return node.val + left_total + right_total