LeetCode ยท #701

Insert into a Binary Search Tree Solution

Follow the BST search path until you reach a null spot, then attach the new value there as a leaf.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Medium

๐Ÿ”—

LeetCode

Problem #701

๐Ÿ—๏ธ

Pattern

BST insert โ€” follow search path

Insert a new value into the BST and return the root of the updated tree. The inserted value is guaranteed not to already exist in the BST.

Example
Input: root = [4,2,7,1,3], val = 5 Output: [4,2,7,1,3,5]
02
Section Two ยท Approach 1

Rebuild from Inorder โ€” Overkill

You could extract all values, insert into a sorted list, and rebuild a BST.

Problem: This throws away the whole benefit of BST insertion. The BST already tells you exactly where the new node belongs in O(h).
03
Section Three ยท Approach 2

Recursive Insert โ€” O(h)

Compare val with the current node and recurse left or right until you hit null. That null position is where the new node should be created.

๐Ÿ’ก Mental model: Search for where the value would be if it were already in the tree. When the search falls off the tree at a null child, that is the insertion point.
Why the return-node pattern works
  • The recursive call returns the updated subtree root.
  • The parent stores it back into node.left or node.right.
  • This naturally rewires the new leaf into the correct position.
Key idea: Insertion never restructures existing nodes in a plain BST. It only attaches one new leaf.
04
Section Four ยท Trace

Visual Walkthrough

Insert 5 into BST [4,2,7,1,3]
Walk the same path as search. 5 > 4 โ†’ go right 5 < 7 โ†’ go left left child is null โ†’ insert new node 5 there New leaf inserted โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” recursive insert
class Solution { public TreeNode insertIntoBST(TreeNode root, int val) { if (root == null) return new TreeNode(val); if (val < root.val) { root.left = insertIntoBST(root.left, val); } else { root.right = insertIntoBST(root.right, val); } return root; } }
Python โ€” recursive insert
class Solution: def insertIntoBST(self, root, val: int): 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
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpace
Rebuild treeO(n)O(n)
BST insertO(h)O(h)
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseWhy it matters
Empty treeThe new node becomes the root.
Insert smallest valueWalk all the way down the left spine.
Insert largest valueWalk all the way down the right spine.
โš  Common Mistake: Forgetting to reassign root.left or root.right from the recursive result. Without that, the new node never gets linked back into the tree.

โ† Back to BST problems