sagelearnai

Insert into a Binary Search Tree

Difficulty: Medium · Pattern: Trees & BST · LeetCode #701

Insert val into a BST and return the root. val is guaranteed not to be in the tree. Use the standard leaf insertion: walk down as if searching and attach a new leaf where the search falls off the tree.

Examples

text
root = [4,2,7,1,3], val = 5  →  [4,2,7,1,3,5]
root = [40,20,60,10,30,50,70], val = 25  →  [40,20,60,10,30,50,70,null,null,25]
root = [], val = 5  →  [5]

Hints

  1. Compare with the current node: go left if val is smaller, otherwise go right.
  2. When the child you need is null, put the new node there.

Approach

Iterative descent, O(h):

text
if root is null: return new node
cur = root
loop:
  if val < cur.val:
      if cur.left is null: cur.left = node; break
      cur = cur.left
  else: (same on the right)

Leaf insertion keeps the BST property because the new node ends up exactly where a search for val would look for it. Repeated inserts can make the tree lopsided (O(n) height), which is why production code uses self-balancing trees (red-black, AVL) or B-trees.

Complexity

Time: O(h). Space: O(1).

Python solution
def insertIntoBST(root, val):
    node = TreeNode(val)
    if not root:
        return node
    cur = root
    while True:
        if val < cur.val:
            if not cur.left:
                cur.left = node
                return root
            cur = cur.left
        else:
            if not cur.right:
                cur.right = node
                return root
            cur = cur.right
JavaScript solution
function insertIntoBST(root, val) {
  const node = new TreeNode(val);
  if (!root) return node;
  let cur = root;
  for (;;) {
    if (val < cur.val) { if (!cur.left) { cur.left = node; return root; } cur = cur.left; }
    else { if (!cur.right) { cur.right = node; return root; } cur = cur.right; }
  }
}