Leetcode 563 Solution
This article provides solution to leetcode question 563 (binary-tree-tilt)
Access this page by simply typing in "lcs 563" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
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