Leetcode #998: Maximum Binary Tree II
In this guide, we solve Leetcode #998 Maximum Binary Tree II 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.

Problem Statement
A maximum tree is a tree where every node has a value greater than any other value in its subtree. You are given the root of a maximum binary tree and an integer val.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Tree, Binary Tree
Intuition
The input is a tree, so recursive decomposition is a natural fit.
We can compute the answer by combining results from left and right subtrees.
Approach
Use DFS and pass the required state through recursive calls.
Combine child results to compute the answer for each node.
Steps:
- Pick traversal order.
- Recurse with state.
- Combine results from children.
Example
Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: a = [1,4,2,3], b = [1,4,2,3,5]
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 insertIntoMaxTree(
self, root: Optional[TreeNode], val: int
) -> Optional[TreeNode]:
if root is None or root.val < val:
return TreeNode(val, root)
root.right = self.insertIntoMaxTree(root.right, val)
return root
Complexity
The time complexity is , and the space complexity is . The space complexity is .
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.