Tensorum
LeetCode 701 · BST

Insert into a Binary Search Tree

LeetCode 701 · Medium · solution, intuition & step-by-step walkthrough

Search for the value; attach at the first empty slot.

MediumTreeBinary Search TreeBinary Tree
91 msruntime · beats 1%
59.5 MBmemory · beats 100%
1approach
1accepted runs · last 9 Jul 2024

This is how I solved Insert into a Binary Search Tree (LeetCode 701), a medium problem from the BST pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Walk down like a search: smaller values go left, larger go right. When the direction you need has no child, that empty spot is where the new value belongs.

Approach

  1. 1

    Empty tree → new node.

  2. 2

    Recurse into the side the value belongs to.

  3. 3

    If that side is empty at this node, attach the new node there.

How I solved it

Recursive descentPythonO(h) time
class Solution:
    def insertIntoBST(self, root, val):
        if root is None:
            return TreeNode(val)
        if root is not None and val > root.val:
            self.insertIntoBST(root.right, val)
        elif root is not None and val < root.val:
            self.insertIntoBST(root.left, val)
        if root is not None and val < root.val and root.left is None:
            root.left = TreeNode(val)
        elif root is not None and val > root.val and root.right is None:
            root.right = TreeNode(val)
        return root
Loading the step-through…

Insert into a Binary Search Tree — FAQ

What is the intuition behind Insert into a Binary Search Tree?

Walk down like a search: smaller values go left, larger go right. When the direction you need has no child, that empty spot is where the new value belongs.

How do you solve Insert into a Binary Search Tree (LeetCode 701)?

1. Empty tree → new node. 2. Recurse into the side the value belongs to. 3. If that side is empty at this node, attach the new node there.

What is the time and space complexity of Insert into a Binary Search Tree?

Time: O(h). Space: O(h). (Accepted approach: Recursive descent.)

What are common mistakes in Insert into a Binary Search Tree?

The cleaner form is root.left = insert(root.left, val).