Leetcode 563 Solution

This article provides solution to leetcode question 563 (binary-tree-tilt)

https://leetcode.com/problems/binary-tree-tilt

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def findTilt(self, root: TreeNode) -> int:
        self.ans = 0

        def dfs(node):
            if node is None:
                return 0

            res = node.val
            left_sum = dfs(node.left)
            right_sum = dfs(node.right)

            self.ans += int(abs(left_sum - right_sum))
            return res + left_sum + right_sum

        dfs(root)
        return self.ans