Leetcode 1021 Solution

This article provides solution to leetcode question 1021 (distribute-coins-in-binary-tree)

https://leetcode.com/problems/distribute-coins-in-binary-tree

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 distributeCoins(self, root: TreeNode) -> int:
        self.ans = 0

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

            lneed = dfs(node.left)
            rneed = dfs(node.right)

            self.ans += abs(lneed) + abs(rneed)
            return lneed + rneed + node.val - 1

        dfs(root)
        return self.ans