Skip to main content

Maximum Product of Splitted Binary Tree - Solution & Explanation

MediumTreeDepth-First SearchBinary Tree16 min readAsked at: Amazon, Microsoft, Meta +2
Practice this problem

Problem Statement

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 * 104].
  • 1 <= Node.val <= 104

Approach Overview

Problem Overview: You are given the root of a binary tree. Remove exactly one edge so the tree splits into two subtrees. The goal is to maximize the product of the sums of the two resulting subtree values.

The key observation: if the total sum of the tree is S and a subtree has sum x, removing the edge above that subtree produces two parts with sums x and S - x. The product becomes x * (S - x). The problem reduces to computing every possible subtree sum and finding the split that maximizes this product.

Approach 1: Recursive Post-order Traversal (O(n) time, O(h) space)

This approach uses Depth-First Search with a post-order traversal of the binary tree. First compute the total sum of the entire tree. Then perform another DFS where each recursive call returns the sum of the current subtree. For each subtree sum x, compute the product x * (totalSum - x) and update the global maximum. Post-order works well because you need both left and right subtree sums before computing the current node’s sum. The recursion stack stores at most the tree height h, giving O(h) auxiliary space.

Approach 2: Iterative Post-order Traversal with Stack (O(n) time, O(n) space)

This version replaces recursion with an explicit stack while still performing post-order traversal on the tree. Nodes are pushed onto the stack and processed after their children, ensuring subtree sums are available before computing the parent sum. A hash map or dictionary stores intermediate subtree sums. Each node contributes exactly once to the total computation, keeping time complexity linear. This approach is useful in languages or environments where recursion depth could cause stack overflow or when you want tighter control over traversal order.

Both approaches rely on the same insight: compute subtree sums and evaluate the product for each possible edge removal. The final answer is returned modulo 1e9 + 7 as required by the problem.

Recommended for interviews: The recursive post-order DFS solution is what interviewers typically expect. It demonstrates strong understanding of subtree aggregation in trees and cleanly computes sums in a single traversal. Mentioning the iterative stack version shows deeper familiarity with traversal mechanics and recursion elimination.

Approach 1: Recursive Post-order Traversal

This method involves two main traversals of the tree:

1. Calculate the total sum of the tree using a post-order traversal.

2. During another post-order traversal, calculate the sum of each subtree and evaluate the potential product if split at that point.

This solution performs a post-order traversal to first calculate the total sum of the tree. It uses another post-order traversal to calculate each subtree sum, and checks the product of the sum of the current subtree and the sum of the rest of the tree. The maximum product found during this traversal is returned.

Code

Python

Java

C++

JavaScript

Complexity

Time Complexity: O(N), where N is the number of nodes. The algorithm performs a constant amount of work for each node.

Space Complexity: O(H), where H is the height of the tree. This space is used by the call stack during recursion.

Try this approach in the editor β†’

Approach 2: Iterative Post-order Traversal with Stack

This approach uses an iterative post-order traversal using a stack to avoid recursion and concurrently calculate subtree sums and products. Carefully pushing nodes onto a stack and maintaining metadata to track progress and necessary calculations allow for this approach.

This C# implementation uses a stack for iterative traversal in a post-order manner. With each loop iteration, it processes nodes and calculates sub-tree sums dynamically, treating the stack as a simulacrum for recursion. This allows for efficient computation without hitting recursion limits, and still evaluates maximum products as it iterates through subtree sums.

Code

C#

Complexity

Time Complexity: O(N), due to each node being evaluated once by following its sequence to the stack until processed.

Space Complexity: O(H), where H is the height of the tree since the stack depth follows the path of the tree.

Try this approach in the editor β†’

Approach 3: Two DFS

We can solve this problem with two DFS traversals.

In the first traversal, we use a sum(root) function to recursively calculate the sum of all nodes in the entire tree, denoted as s.

In the second traversal, we use a dfs(root) function to recursively traverse each node and calculate the sum of nodes in the subtree rooted at the current node, denoted as t. After splitting at the current node and its parent, the sums of the two subtrees are t and s - t respectively, and their product is t times (s - t). We traverse all nodes to find the maximum product, which is the answer.

The time complexity is O(n), and the space complexity is O(n), where n is the number of nodes in the binary tree.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor β†’

Complexity Comparison

ApproachComplexity
Recursive Post-order Traversal

Time Complexity: O(N), where N is the number of nodes. The algorithm performs a constant amount of work for each node.

Space Complexity: O(H), where H is the height of the tree. This space is used by the call stack during recursion.

Iterative Post-order Traversal with Stack

Time Complexity: O(N), due to each node being evaluated once by following its sequence to the stack until processed.

Space Complexity: O(H), where H is the height of the tree since the stack depth follows the path of the tree.

Two DFSβ€”

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive Post-order TraversalO(n)O(h)Best general solution. Clean implementation when recursion depth is manageable.
Iterative Post-order Traversal with StackO(n)O(n)Useful when avoiding recursion or handling very deep trees.

Video Solution

Maximum Product of Splitted Binary Tree | Simple Intuition | Leetcode 1339 | codestorywithMIK β€’ codestorywithMIK β€’ 15,970 views views

Watch 9 more video solutions β†’

Frequently Asked Questions

Is Maximum Product of Splitted Binary Tree easy or hard?
Maximum Product of Splitted Binary Tree is generally considered a medium difficulty problem. The traversal itself is straightforward, but recognizing that every subtree sum represents a possible split requires understanding how edge removal affects tree partitions.
Maximum Product of Splitted Binary Tree Python/Java solution
Python and Java solutions typically implement recursive post-order DFS. Each recursive call returns the sum of the current subtree while updating a global maximum product. The final result is returned modulo 1e9 + 7 after evaluating all possible subtree splits.
How to solve Maximum Product of Splitted Binary Tree in O(n)?
First compute the total sum of the entire tree using DFS. Then perform a post-order traversal where each node returns its subtree sum. For every subtree sum x, calculate x * (totalSum - x) and track the maximum product. Because each node is visited once, the algorithm runs in O(n) time.
What is the best approach for Maximum Product of Splitted Binary Tree?
The most efficient approach uses post-order depth-first search to compute subtree sums. After calculating the total tree sum, each subtree sum x is evaluated with the formula x * (totalSum - x). This checks the product created if the edge above that subtree is removed. The algorithm runs in O(n) time because every node is processed once.
Is Maximum Product of Splitted Binary Tree asked at Google/Amazon/Meta?
Tree and DFS problems with subtree aggregation frequently appear in interviews at companies like Amazon, Google, and Meta. Variations of splitting trees or computing subtree metrics are common because they test understanding of depth-first traversal and recursive reasoning.
What data structure is used in Maximum Product of Splitted Binary Tree?
The problem primarily uses a binary tree along with depth-first search traversal. Recursive implementations rely on the call stack, while iterative versions use an explicit stack to simulate post-order traversal. Some implementations also store subtree sums in a list or hash map.
What is the time complexity of Maximum Product of Splitted Binary Tree?
The optimal solution runs in O(n) time where n is the number of nodes in the binary tree. A DFS traversal computes the total sum and all subtree sums in linear time. Space complexity is O(h) for recursion stack depth, where h is the tree height.

Ready to solve this problem?

Practice Maximum Product of Splitted Binary Tree with our built-in code editor and test cases.

Practice on FleetCode