.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

 

Comments