Distribute Coins in Binary Tree — LeetCode 979 Python Solution

MediumTreeDepth-First SearchBinary Tree
Problem
#979
Reading time
3 min

The problem

You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.

Example

Input
root = [3,0,0]
Output
2
Explanation
From the root of the tree, we move one coin to its left child, and one coin to its right child.

Python solution

Python
# 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:
        def dfs(root):
            if root is None:
                return 0
            left, right = dfs(root.left), dfs(root.right)
            nonlocal ans
            ans += abs(left) + abs(right)
            return left + right + root.val - 1

        ans = 0
        dfs(root)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(h) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 979. Distribute Coins in Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 979. Distribute Coins in Binary Tree?
LeetCode 979. Distribute Coins in Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 979. Distribute Coins in Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 979. Distribute Coins in Binary Tree?
The Python solution on this page uses O(h) auxiliary space.
What topics does LeetCode 979. Distribute Coins in Binary Tree cover?
LeetCode 979. Distribute Coins in Binary Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview