Data Structures & Algorithms Binary Search Trees
💡
Exercise 98

Insert into BST 15 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Given a BST and a value, insert the value into the BST and return the root. The new node always becomes a leaf — you never need to restructure the tree.

# 4 4 # / \ insert 5 / \ # 2 7 ────────→ 2 7 # / \ / \ / # 1 3 1 3 5

The insertion algorithm is just search until you find an empty spot:

  • If the current node is None, create a new node here
  • If val < node.val, insert into the left subtree
  • If val > node.val, insert into the right subtree
  • Return the (possibly new) root

The recursive solution is beautifully simple — each recursive call either goes deeper or creates the new node.

📋 Instructions
Implement `insert_bst(root, val)` recursively. Insert 5 into the tree and print inorder traversal.
Base case: if not root, return TreeNode(val). If val < root.val, root.left = insert_bst(root.left, val). If val > root.val, root.right = insert_bst(root.right, val). Return root.
🧪 Test Cases
Input
inorder(root)
Expected
[1, 2, 3, 4, 7]
Test case 1
Input
inorder(root)
Expected
[1, 2, 3, 4, 5, 7]
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.