LeetCode solutions

1040. Maximum Binary Tree II

My accepted Python solution to LeetCode problem 1040, Maximum Binary Tree II, running in 0ms.

  • Difficulty: Medium
  • Python
  • Runtime 0ms
  • Memory 17.3MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 0ms, memory 17.3MB, accepted 2026-01-02.

python
# 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 val is greater than root, new node becomes root
        if not root or val > root.val:
            new_node = TreeNode(val)
            new_node.left = root
            return new_node
        
        # Otherwise, insert into right subtree
        root.right = self.insertIntoMaxTree(root.right, val)
        return root

Source