Problem 1339

Abstract / Summary

Given a binary tree with node values, split it into two by removing one edge to maximize the product of the sums of the resulting subtrees.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1339.py

class Solution:
    def maxProduct(self, root: Optional[TreeNode]) -> int:
        # sum of subtree, including node itself
        @cache
        def subtree(node):
            return node.val + subtree(node.left) + subtree(node.right) if node else 0

        # sum of the whole tree
        total = subtree(root)

        result = 0
        def deeper(node):
            if not node:
                return 0

            one = subtree(node.left)
            two = subtree(node.right)

            best = max(one * (total - one), two * (total - two))
            best = max(best, deeper(node.left), deeper(node.right))
            return best

        return deeper(root) % 1_000_000_007
23 lines | 712 bytes | submitted December 15, 2023 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (400k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a method maxProduct that computes the maximum product obtainable by splitting a binary tree into two non-empty subtrees. The algorithm works in two phases: first it determines the sum of every possible subtree, then it evaluates each potential split to find the product of the sums of the two resulting parts. The final answer is returned modulo 1 000 000 007.

Subtree Sum Computation

A nested function subtree is declared with the @cache decorator. This memoized helper returns the sum of the values contained in a given node’s entire subtree, including the node itself. The definition is concise:

@cache
def subtree(node):
    return node.val + subtree(node.left) + subtree(node.right) if node else 0

The conditional expression ensures that a None reference contributes zero to the sum, which naturally handles leaf children. Because the result of each call is cached, any subsequent request for the same node’s sum is retrieved instantly without recomputing the entire descendant chain.

Total Tree Sum

Immediately after defining subtree, the code computes the sum of the whole tree by invoking subtree on the root:

total = subtree(root)

This single call populates the cache with the sum for every node in the tree, establishing a foundation for the next phase.

Evaluating Split Products

The core of the algorithm resides in the recursive function deeper. It traverses the tree, considering each node as a potential split point. For a given node, the sums of its left and right subtrees are obtained from the cached subtree function:

one = subtree(node.left)
two = subtree(node.right)

The product of a split that separates the left subtree from the rest of the tree is one * (total - one). Similarly, separating the right subtree yields two * (total - two). The larger of these two products is stored in best. The function then recursively explores deeper nodes, propagating the maximum product found so far:

best = max(one * (total - one), two * (total - two))
best = max(best, deeper(node.left), deeper(node.right))
return best

The recursion terminates when a None node is encountered, returning zero, which does not affect the maximum calculation.

Finally, the method returns the best product modulo the required prime:

return deeper(root) % 1_000_000_007

Edge Cases Handled

When the input tree is empty (root is None), the subtree call yields zero, and the subsequent deeper call immediately returns zero. The modulo operation then yields zero as the final result, correctly reflecting that no split is possible.

If the tree consists of a single node, both left and right subtree sums are zero. The product calculations involve 0 * (total - 0), which also results in zero. The recursion does not find any deeper nodes, so the method returns zero, indicating that a split cannot produce two non-empty parts.

The use of the conditional expression if node else 0 in subtree guarantees that leaf children (None) are safely treated as having a sum of zero, preventing attribute errors and ensuring correct arithmetic for all leaf configurations.

Performance Optimizations

The most significant optimization is the memoization of subtree sums via the @cache decorator. By storing the result of each subtree call, the algorithm avoids recomputing the same sums during the deeper traversal, reducing redundant work dramatically, especially for large or unbalanced trees.

Computing the total sum once, before any split evaluation, eliminates the need to recompute the overall tree sum for each candidate split. The cached subtree sums are then reused to calculate total - one and total - two instantly.

The recursion in deeper only accesses already-computed sums, making each node’s contribution to the final answer a constant-time operation. The modulo operation is deferred until the very end, preventing repeated reductions during intermediate calculations and preserving integer precision throughout the traversal.

Overall, the combination of caching, single-pass total computation, and deferred modulo yields an implementation that scales efficiently with the size of the input tree while maintaining clear and concise logic.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big family tree filled with toys. Each person in this tree is holding a number. This code is trying to find the best way to cut the tree into two smaller pieces so that when you multiply the total number of toys in one piece by the total number of toys in the other, you get the biggest number possible.

First, the code goes through every part of the tree to add up all the numbers. It remembers these totals so it can quickly look them up later like looking at a cheat sheet. This helps figure out how many toys are in any branch of the tree without counting them over and over again.

Next, the code starts looking at every connection between the family members to see what would happen if that connection was snipped. When it snips a connection, it looks at the branch that falls away, counts how many toys are in that branch, and then figures out how many toys are left in the rest of the tree. It multiplies those two piles of toys together to see if it found a record-high number. It keeps crawling deeper into the tree, checking every single spot where a cut could be made, and it keeps track of the biggest result it discovers. Finally, because the number might get really, really large, it keeps only the remainder after dividing by a very big number to keep things organized.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.74 | σ = 1.46

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
fartem Ruby
fpdjsns C++
fsq C++
JoshCrozier JS
lkwq007 Python
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
fartem Ruby
fpdjsns C++
fsq C++
JoshCrozier JavaScript
lkwq007 Python
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
withaarzoo C++
27 links | 16 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

7 solutions   December 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality