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.

In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.

Return the minimum number of moves required to make every node have exactly one coin.

Example 1:

!https://assets.leetcode.com/uploads/2019/01/18/tree1.png

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.

Example 2:

!https://assets.leetcode.com/uploads/2019/01/18/tree2.png

Input: root = [0,3,0]
Output: 3
Explanation:From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.

Constraints:

  • The number of nodes in the tree is n.
  • 1 <= n <= 100
  • 0 <= Node.val <= n
  • The sum of all Node.val is n.
/**
 * 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 {
    private int moves = 0;
    public int distributeCoins(TreeNode root) {
        dfs(root);
        return moves;
    }
    private int dfs(TreeNode node) {
        if (node == null) return 0;

        // 좌우 자식 노드의 과잉 또는 부족 코인 수를 계산
        int left = dfs(node.left);
        int right = dfs(node.right);

        // 이동 수 누적
        moves += Math.abs(left) + Math.abs(right);

        // 현재 노드의 코인 수 반환, 1은 root 꺼 하나 
        return node.val + left + right - 1;
    }
}

 

'알고리즘' 카테고리의 다른 글

알고리즘 펜윅 트리  (2) 2024.08.11
35. Search Insert Position  (0) 2024.06.07
밀렸던 릿코드 풀기 (232, 150, 739, 2966, 1291)  (0) 2024.02.03
kakao_광고삽입  (0) 2021.12.06
kakao_표편집  (0) 2021.12.06