#998

Maximum Binary Tree II

Medium
TreeBinary TreeTreeRecursion
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

Instead of reconstructing the entire array, we can directly insert the new value into the tree. We traverse the tree to find the appropriate position for the new value while maintaining the properties of the maximum binary tree.

⚙️

Algorithm

2 steps
  1. 1Step 1: If the new value is greater than the root's value, create a new root with the new value, and make the current root its left child.
  2. 2Step 2: If the new value is less than or equal to the root's value, recursively insert the new value into the right subtree.
solution.py13 lines
1class TreeNode:
2    def __init__(self, val=0, left=None, right=None):
3        self.val = val
4        self.left = left
5        self.right = right
6
7    def insertIntoMaxTree(self, root, val):
8        if val > root.val:
9            new_root = TreeNode(val)
10            new_root.left = root
11            return new_root
12        root.right = self.insertIntoMaxTree(root.right, val)
13        return root

Complexity note: The time complexity is O(n) because in the worst case, we may traverse the entire height of the tree. The space complexity is O(1) as we are not using any additional data structures.

  • 1Understanding the properties of a maximum binary tree is crucial.
  • 2Directly manipulating the tree structure can be more efficient than reconstructing arrays.

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