#654

Maximum Binary Tree

Medium
ArrayDivide and ConquerStackTreeMonotonic StackBinary TreeDivide and ConquerRecursion
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 solution uses a recursive approach but avoids repeated scans by leveraging the maximum value's index directly. This reduces the time complexity significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a helper function that takes the start and end indices of the current subarray.
  2. 2Step 2: Find the maximum value and its index in the current subarray.
  3. 3Step 3: Create a root node and recursively build the left and right subtrees using the indices.
solution.py16 lines
1class TreeNode:
2    def __init__(self, val):
3        self.val = val
4        self.left = None
5        self.right = None
6
7def constructMaximumBinaryTree(nums):
8    def buildTree(start, end):
9        if start > end:
10            return None
11        max_index = start + nums[start:end + 1].index(max(nums[start:end + 1]))
12        root = TreeNode(nums[max_index])
13        root.left = buildTree(start, max_index - 1)
14        root.right = buildTree(max_index + 1, end)
15        return root
16    return buildTree(0, len(nums) - 1)

Complexity note: This complexity is linear because we only traverse the array once to find the maximum value for each recursive call, leading to a total of O(n) operations.

  • 1Finding the maximum value efficiently is crucial for performance.
  • 2Recursive tree construction mirrors the problem's divide-and-conquer nature.

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