Maximum Binary Tree II - Problem
A maximum binary tree is a fascinating data structure where every node has a value greater than any value in its subtree. Think of it as a hierarchy where each parent is always the "boss" of everyone below them!
You're given the root of an existing maximum binary tree and a new integer val. The original tree was built using this process:
- Find the largest element in the array - this becomes the root
- Everything to the left of the max becomes the left subtree
- Everything to the right of the max becomes the right subtree
- Recursively apply this process
Your mission: Add val to the end of the original array and return the new maximum binary tree that would be constructed from this extended array.
For example, if the original array was [3,2,1,6,0,5] and val = 4, you need to return the tree that would be built from [3,2,1,6,0,5,4].
Input & Output
example_1.py — Basic Insertion
$
Input:
root = [4,1,3,null,null,2], val = 5
›
Output:
[5,4,null,1,3,null,null,2]
💡 Note:
Since 5 > 4 (root), the new value 5 becomes the root of the entire tree, with the original tree becoming its left child.
example_2.py — Right Subtree Insertion
$
Input:
root = [5,2,4,null,1], val = 3
›
Output:
[5,2,4,null,1,3]
💡 Note:
Since 3 < 5 (root), we traverse the right subtree. 3 < 4, so it doesn't replace 4, and becomes a new right child of 4.
example_3.py — New Root Creation
$
Input:
root = [5,2,3,null,1], val = 6
›
Output:
[6,5,null,2,3,null,1]
💡 Note:
Since 6 > 5 (root), val becomes the new root with the original tree as its left subtree.
Constraints
- The number of nodes in the tree is in the range [1, 100]
- 1 ≤ Node.val ≤ 100
- All the values of the tree are unique
- 1 ≤ val ≤ 100
- It's guaranteed that val does not exist in the original tree
Visualization
Tap to expand
Understanding the Visualization
1
Check New Authority
When a new person joins, check if they have higher authority than the current CEO
2
Promote or Place
If yes, they become new CEO with old hierarchy as their department. If no, find their spot in the rightmost chain
3
Maintain Hierarchy
Since they joined 'at the end', they can only affect the rightmost reporting chain
4
Final Structure
The hierarchy maintains the property that every manager outranks their entire department
Key Takeaway
🎯 Key Insight: Since the new value is appended to the end of the original array, it can only affect the rightmost path of the maximum binary tree, leading to an elegant O(h) time solution.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code