Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1339: Maximum Product of Splitted Binary Tree

In this guide, we solve Leetcode #1339 Maximum Product of Splitted Binary Tree in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Tree, Depth-First Search, Binary Tree

Intuition

We need to explore a structure deeply before backing up, which suits DFS.

DFS keeps local context on the call stack and is easy to implement recursively.

Approach

Define a recursive DFS that carries the necessary state.

Combine child results as the recursion unwinds.

Steps:

  • Define a recursive DFS with state.
  • Visit children and combine results.
  • Return the final aggregation.

Example

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)

Python Solution

# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxProduct(self, root: Optional[TreeNode]) -> int: def sum(root: Optional[TreeNode]) -> int: if root is None: return 0 return root.val + sum(root.left) + sum(root.right) def dfs(root: Optional[TreeNode]) -> int: if root is None: return 0 t = root.val + dfs(root.left) + dfs(root.right) nonlocal ans, s if t < s: ans = max(ans, t * (s - t)) return t mod = 10**9 + 7 s = sum(root) ans = 0 dfs(root) return ans % mod

Complexity

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

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy