979. Distribute Coins in Binary Tree
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 |
댓글
이 글 공유하기
다른 글
-
알고리즘 펜윅 트리
알고리즘 펜윅 트리
2024.08.11시작펜윅 트리, 세그먼트 트리에서 변형된 형태입니다. 대표적으로 구간 합 알고리즘을 O(N)보다 빠르게 풀고자 할 때 펜윅 트리를 사용합니다.일반적으로 구간 합을 구할 때 O(N) 정도의 시간이 걸립니다.펜윅 트리(BIT = Binary Indexed Tree) 이용하게 되면 O(logN) 으로 시간 복잡도를 감소 시킬 수 있습니다. 전체 노드의 부분 합 즉, 0~K 합을 구해 두게 되면 원하는 구간 합 S~D를 구하는 것이 가능해 집니다. (Start ~ Destination)O(logN) 의 수행시간 만으로 구간합을 구할 수 있게 됩니다. 구간 합 외에도 같은 원리로 업데이트도 수행할 수 있게 됩니다. 펜윅트리 구조일반적으로 펜윅 트리 구조는 아래와 같이 세그먼트 트리를 응용한 형태로 구조를 정형화… -
35. Search Insert Position
35. Search Insert Position
2024.06.07문제 정의 주어진 정렬된 배열에서 목표 값을 찾고, 찾지 못하면 목표 값이 삽입될 인덱스를 반환하는 문제입니다. 이 문제는 O(log n) 시간 복잡도로 해결해야 합니다. https://leetcode.com/problems/search-insert-position/description/Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity…. -
밀렸던 릿코드 풀기 (232, 150, 739, 2966, 1291)
밀렸던 릿코드 풀기 (232, 150, 739, 2966, 1291)
2024.02.03 -
kakao_광고삽입
kakao_광고삽입
2021.12.06
댓글을 사용할 수 없습니다.