Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 블라인드박스
- DIY
- 게임
- 가챠
- LeetCode
- 맛집
- javascript
- 지쿠악스
- 30mf
- 노노그램
- 메탈퍼즐
- 제프딕슨
- 밥무하마드
- 바질토마토뭐시기
- 미앤아이
- 건담
- 우리시대의역설
- 포켓몬
- 프라모델
- 코테
- 롱라이플
- 유루건
- 발더스모드
- 누룽지소금빵
- 코딩테스트
- 취미
- 눈알빠지겠네
- 발더스게이트
- 지리데칼
- 건담헤드
Archives
- Today
- Total
.Zzumbong
[leetCode/JS] 1339. Maximum Product of Splitted Binary Tree 본문
coding test/leetCode
[leetCode/JS] 1339. Maximum Product of Splitted Binary Tree
쭘봉 2026. 1. 7. 09:41난이도 [ 🤔 ] Medium
문제 설명
Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7. Note that you need to maximize the answer before taking the mod and not after taking it.
입출력 예
Example 1:

Input: root = [1,2,3,4,5,6]
Output: 110
Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)
Example 2:

Input: root = [1,null,2,3,4,null,null,5,6]
Output: 90
Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)
Constraints
- The number of nodes in the tree is in the range [2, 5 * 10^4].
- 1 <= Node.val <= 10^4
내 솔루션
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxProduct = function (root) {
const MOD = 1000000007;
// DFS로 순회하면서 현재 트리 합을 계속 저장하면서
// 전체 합을 구해두기
const allSums = [];
const getSum = (node) => {
if (!node) return 0;
const currentSum = node.val + getSum(node.left) + getSum(node.right);
allSums.push(currentSum);
return currentSum;
}
const totalSum = getSum(root)
let maxProd = 0;
for (let sum of allSums) {
const currentProd = sum * (totalSum - sum);
if (currentProd > maxProd) {
maxProd = currentProd;
}
}
return maxProd % MOD
};
감상평
- array push 가 아니라 그때그때 비교하는 코드로 만들면 더 빠름
- MOD 하는거 0 몇개인지 자꾸 햇갈려 1-0은 8개-7

'coding test > leetCode' 카테고리의 다른 글
| [leetCode/JS] 1161. Maximum Level Sum of a Binary Tree (0) | 2026.01.06 |
|---|---|
| [leetCode/JS] 1975. Maximum Matrix Sum (0) | 2026.01.05 |
| [leetCode/JS] 66. Plus One (0) | 2026.01.02 |
| [leetCode/JS] 1970. Last Day Where You Can Still Cross (1) | 2025.12.31 |
| [leetCode/JS] 3074. Apple Redistribution into Boxes (0) | 2025.12.29 |
Comments
