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릿코드 문제가 영어라 접근하기 쉽지 않지만 그래도 풀어보면 자료구조에 대해 이해할 수 있어서 좋은점이 많다. 첫문제는 비교적 쉬운 문제이다. 232. Implement Queue using Stacks 처음에 접근할 때는 HashSet 을 사용해보려고 했는데 순서가 보장이 안되더라… 왜냐하면 내부적으로 해시테이블을 구현하는데 해시함수에 의해서 순서가 달라진다. LinkedHashSet을 이용하면 풀 수 있을거 같다.(+ 정렬되어있다면 TreeSet을 이용할 수 있다. 추가, 삭제, 조회 작업시 O(logn) 으로 수행된다. ) 근데 접근하기 편한 ArrayList 를 써서 풀었다. 😎 Time Complexity push - O(1) pop - O(n) //비효율적 peek - O(1) empty - … -
kakao_광고삽입
kakao_광고삽입
2021.12.06광고 삽입 문제 설명 카카오TV에서 유명한 크리에이터로 활동 중인 죠르디는 환경 단체로부터 자신의 가장 인기있는 동영상에 지구온난화의 심각성을 알리기 위한 공익광고를 넣어 달라는 요청을 받았습니다. 평소에 환경 문제에 관심을 가지고 있던 "죠르디"는 요청을 받아들였고 광고효과를 높이기 위해 시청자들이 가장 많이 보는 구간에 공익광고를 넣으려고 합니다. "죠르디"는 시청자들이 해당 동영상의 어떤 구간을 재생했는 지 알 수 있는 재생구간 기록을 구했고, 해당 기록을 바탕으로 공익광고가 삽입될 최적의 위치를 고를 수 있었습니다. 참고로 광고는 재생 중인 동영상의 오른쪽 아래에서 원래 영상과 동시에 재생되는 PIP(Picture in Picture) 형태로 제공됩니다. 다음은 "죠르디"가 공익광고가 삽입될 최적…
댓글을 사용할 수 없습니다.