#1339

Maximum Product of Splitted Binary Tree

Medium
TreeDepth-First SearchBinary TreeDepth-First Search (DFS)Tree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach calculates the total sum of the tree once and then uses a single traversal to compute the maximum product by leveraging the relationship between the total sum and subtree sums.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total sum of the binary tree in one traversal.
  2. 2Step 2: During the same traversal, calculate the sum of each subtree and compute the product with the remaining tree sum.
  3. 3Step 3: Keep track of the maximum product found during the traversal.
solution.py26 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class Solution:
9    def maxProduct(self, root: TreeNode) -> int:
10        total_sum = self.tree_sum(root)
11        self.max_product = 0
12        self.calculate_product(root, total_sum)
13        return self.max_product % (10**9 + 7)
14
15    def tree_sum(self, node):
16        if not node:
17            return 0
18        return node.val + self.tree_sum(node.left) + self.tree_sum(node.right)
19
20    def calculate_product(self, node, total_sum):
21        if not node:
22            return 0
23        subtree_sum = node.val + self.calculate_product(node.left, total_sum) + self.calculate_product(node.right, total_sum)
24        product = subtree_sum * (total_sum - subtree_sum)
25        self.max_product = max(self.max_product, product)
26        return subtree_sum

Complexity note: The time complexity is O(n) because we traverse the tree once to calculate the total sum and again to calculate the maximum product, leading to linear operations.

  • 1Understanding the relationship between subtree sums and the total sum is crucial for optimizing the solution.
  • 2Using a single traversal to gather necessary data can significantly reduce time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.