Problem 998

Abstract / Summary

Given a list of integers and a previously constructed maximum binary tree from them, add a new integer and return the updated maximum binary tree.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0998.py

class Solution:
    # by far the hardest part is understanding the problem description
    def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if not root:
            return TreeNode(val, root)
        if root.val < val:
            return TreeNode(val, root)

        root.right = self.insertIntoMaxTree(root.right, val)
        return root
10 lines | 396 bytes | submitted August 2, 2024 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 71% (60k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class containing a single method insertIntoMaxTree. This method receives the root of a binary max-tree and an integer val, and returns the root of a new tree that results from inserting val while preserving the max-tree property. The algorithm proceeds recursively, handling three distinct situations: an empty subtree, a value larger than the current node, and the general case where the value must be placed somewhere in the rightmost chain of the tree.

Key Steps

Handling an empty subtree

When the recursion reaches a None reference, a new TreeNode is created with val as its value. The newly created node becomes the leaf of the tree at that position.

if not root:
    return TreeNode(val, root)

The second argument to TreeNode (the left child) is explicitly passed as root, which is None in this branch, making the intent clear and avoiding reliance on default constructor behavior.

Inserting a new maximum at the current position

If the current node’s value is smaller than val, the algorithm creates a new node whose left child is the entire existing subtree. This operation lifts the existing subtree beneath the new maximum, satisfying the max-tree invariant that each node is larger than all nodes in its left subtree.

if root.val < val:
    return TreeNode(val, root)

By returning the newly created node directly, the method avoids any additional restructuring of the right side of the tree.

Recursing down the right spine

When val is not larger than the current node, the algorithm proceeds to the right child, because in a max-tree all values smaller than the root are placed in the right subtree while preserving the original order. The recursive call updates root.right with the result of the insertion, and the original root is returned unchanged.

root.right = self.insertIntoMaxTree(root.right, val)
return root

This step ensures that the insertion respects the original right-most ordering of the tree.

Edge Cases Addressed

The code explicitly covers the scenario where the input tree is completely empty. By checking if not root first, it guarantees that a valid TreeNode is always returned, even when the original tree has no nodes.

Another edge case occurs when the new value is greater than the value at the root of the current (sub)tree. In that situation the algorithm creates a new node that becomes the parent of the entire existing subtree, correctly handling the case where the new value should become the new overall maximum.

Finally, the recursion naturally terminates when it reaches a leaf node whose right child is None. At that point the if not root branch creates the new leaf, ensuring that insertion at the far right end of the tree is handled without special-case code.

Performance Optimizations

The implementation minimizes object creation by constructing a new TreeNode only when it is necessary: either for an empty subtree or when the new value becomes a new maximum. In the common case where the value is inserted somewhere deeper in the right spine, the algorithm reuses the existing nodes and only updates a single pointer (root.right).

Recursive descent follows the rightmost path exclusively, which matches the structure of a max-tree where larger values are always positioned closer to the root. This targeted traversal avoids unnecessary exploration of the left subtree, reducing the number of recursive calls to the depth of the right spine.

By returning the newly created node directly when it becomes the new root of a subtree, the code eliminates the need for additional re-linking steps after the recursive call returns. This direct return pattern streamlines the control flow and keeps the call stack shallow relative to the depth of the insertion point.

Overall, the algorithm achieves insertion with a single pass down the right side of the tree, allocating at most one new node, and updating only the necessary pointer, which together constitute the primary performance benefits of this implementation.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a tree made of numbers where the biggest number is always perched at the very top. When a new number arrives, it wants to find its perfect spot in this family. First, the tree looks at the top number. If the new number is bigger than the top one, the new number becomes the new boss and pushes the entire old tree down to be one of its branches. If the new number is smaller, it travels down the right side of the tree to see if it can find a home there instead. This process happens over and over until the new number finally lands in a spot where it fits just right.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.26 | σ = 1.62

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
fartem Ruby
fsq C++
Garvit244 Python
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
fartem Ruby
fsq C++
Garvit244 Python
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
32 links | 17 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
1 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 solutions   August 2, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality