979. Distribute Coins in Binary Tree

Back to Homepage   |     Back to Code List


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int total = 0;
    public int distributeCoins(TreeNode root) {
        helper(root);
        return total;
    }
    
    private int helper(TreeNode root) {
        if (root == null) return 0;
        int left = helper(root.left);
        total += Math.abs(left);
        int right = helper(root.right);
        total += Math.abs(right);
        
        return left + right + root.val - 1;
    }
}