979. Distribute Coins in Binary Tree

Tapan RachchhTapan Rachchh
1 min read
# 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 distributeCoins(self, root: Optional[TreeNode]) -> int:
        moves = 0
        def dfs(node, excess): 
            nonlocal moves

            if not node:
                return 0

            excessLeft = dfs(node.left, excess)
            excessRight = dfs(node.right, excess)

            # excess coins at a level (self + left + right)
            excess = node.val - 1 + excessLeft + excessRight

            moves += abs(excessLeft) + abs(excessRight)

            return excess 


        dfs(root, 0)

        return moves
0
Subscribe to my newsletter

Read articles from Tapan Rachchh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tapan Rachchh
Tapan Rachchh