Insert into a Binary Search Tree — LeetCode 701 Python Solution

MediumTreeBinary Search TreeBinary Tree
Problem
#701
Reading time
3 min

The problem

You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion.

Example

Input
root = [4,2,7,1,3], val = 5
Output
[4,2,7,1,3,5]
Explanation
Another accepted tree is:

Python solution

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 insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if root is None:
            return TreeNode(val)
        if root.val > val:
            root.left = self.insertIntoBST(root.left, val)
        else:
            root.right = self.insertIntoBST(root.right, val)
        return root

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 701. Insert into a Binary Search Tree is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Tree, Binary Tree and Binary Search Tree.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 701. Insert into a Binary Search Tree?
LeetCode 701. Insert into a Binary Search Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 701. Insert into a Binary Search Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 701. Insert into a Binary Search Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 701. Insert into a Binary Search Tree cover?
LeetCode 701. Insert into a Binary Search Tree is tagged Tree, Binary Search Tree and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview