Insert into a Binary Search Tree - 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.

It is guaranteed that the new value does not exist in the original BST.

Notice: There may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

Input & Output

Example 1 — Insert into Right Subtree
$ Input: root = [4,2,7,1,3], val = 5
Output: [4,2,7,1,3,5]
💡 Note: Start at root (4): 5 > 4 so go right to 7. At node 7: 5 < 7 so go left. Left child is null, so insert 5 there.
Example 2 — Insert into Left Subtree
$ Input: root = [40,20,60,10,30,50,70], val = 25
Output: [40,20,60,10,30,50,70,null,null,25]
💡 Note: 25 < 40 (go left) → 25 > 20 (go right) → 25 < 30 (go left). Insert 25 as left child of 30.
Example 3 — Single Node Tree
$ Input: root = [4], val = 2
Output: [4,2]
💡 Note: Tree has only root node 4. Since 2 < 4, insert 2 as left child of root.

Constraints

  • The number of nodes in the tree will be in the range [0, 104]
  • -108 ≤ Node.val ≤ 108
  • All the values Node.val are unique
  • -108 ≤ val ≤ 108
  • It's guaranteed that val does not exist in the original BST

Visualization

Tap to expand
Insert 5 into BST: Input → Process → OutputInput Tree42713Insert value: 5BST Navigation475>4 →← 5<75Insert as left childResult Tree427135Output: [4,2,7,1,3,5]BST Property Maintained: Left < Node < RightOptimal Time: O(h) | Space: O(h) where h = tree height
Understanding the Visualization
1
Input BST
Given tree [4,2,7,1,3] and value 5 to insert
2
Navigate Tree
Follow BST property: 5>4 (right), 5<7 (left)
3
Insert Node
Create new node 5 as left child of 7
Key Takeaway
🎯 Key Insight: BST property guarantees exactly one valid insertion position for any new value
Asked in
Amazon 42 Microsoft 38 Facebook 29 Google 24
87.4K Views
Medium Frequency
~15 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen