Problem 701

Abstract / Summary

Given the root of a binary search tree and a value insert it into the correct position and return the root.

Note

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

Python 0701.py

class Solution:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if not root:
            return TreeNode(val)

        if val < root.val:
            root.left  = self.insertIntoBST(root.left,  val)
        else:
            root.right = self.insertIntoBST(root.right, val)
        return root
10 lines | 351 bytes | submitted September 14, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (1+ million submissions).

Typical patterns to solve this problem:
  • Binary Search Tree
  • 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 method insertIntoBST that inserts a new integer value into a binary search tree (BST) while preserving the BST ordering invariant. The method is recursive, handling the base case of an empty subtree by creating a new node, and otherwise delegating the insertion to the appropriate child based on a comparison between the target value and the current node’s value. The function ultimately returns the (potentially unchanged) root of the tree, allowing the caller to receive the updated structure.

Key Steps

The algorithm proceeds through a clear sequence of logical decisions, each reflected in a concise code fragment.

The first decision checks whether the current subtree is empty:

if not root:
    return TreeNode(val)

When the subtree is empty, a new TreeNode containing the insertion value is instantiated and returned, establishing the leaf position for the new element.

If the subtree is not empty, the algorithm compares the insertion value with the current node’s value to decide the direction of traversal:

if val < root.val:
    root.left  = self.insertIntoBST(root.left,  val)
else:
    root.right = self.insertIntoBST(root.right, val)

The recursive call replaces the appropriate child pointer (left or right) with the result of the deeper insertion, ensuring that any newly created node is correctly linked into the tree.

Finally, the method returns the original root node, now possibly augmented with the new value somewhere in its descendants:

return root

Edge Cases Handled

The recursion naturally accommodates several edge conditions without additional code. When the tree consists of a single node, the comparison directs the insertion to either the left or right child, which is initially None. The base-case clause then creates the new node, effectively handling the insertion into an empty child slot.

If the insertion value is equal to an existing node’s value, the algorithm follows the else branch, treating the value as greater than or equal and inserting it into the right subtree. This deterministic handling of duplicates ensures that the tree remains a valid BST according to the convention that duplicates reside on the right side.

When the input root itself is None, the method immediately creates and returns a new node, covering the scenario of constructing a BST from scratch.

Performance Optimizations

The implementation leverages recursion to avoid explicit stack management, allowing the Python interpreter to handle call frames efficiently. By directly assigning the result of the recursive call back to the corresponding child pointer, the code eliminates the need for auxiliary variables or temporary structures, reducing memory overhead.

The comparison val < root.val is performed once per recursive level, and the subsequent branch executes a single recursive call, ensuring that each node is visited at most once along the path from the root to the insertion point. This direct path traversal minimizes unnecessary work and aligns with the optimal behavior for BST insertion.

The use of early return when encountering a None subtree prevents further recursion, terminating the process as soon as the correct insertion location is found. This early exit contributes to a tight execution path and avoids superfluous function calls.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a family tree where every house has a special rule for where to park a car. This tree is built so that smaller numbers always go to the left side and larger numbers always go to the right side. When a new car with a number on it arrives, the computer starts at the very top of the tree. If the top house is empty, the computer just parks the car right there. If the new car has a smaller number than the one already in the house, the computer moves to the left to look for a spot. If the new car has a bigger number, the computer moves to the right instead. The computer keeps moving down the tree, checking left and right, until it finds an empty space that follows all the rules. Once it finds that spot, it parks the car there.

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 = 9 | μ = 8.48 | σ = 0.79

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

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 Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github AdelDaniel Dart
BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
AdelDaniel Dart
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
37 links | 24 authors | 10 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 easy
3 solutions   September 14, 2023

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