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 into a Binary Search Tree INPUT Original BST: 4 2 7 1 3 root = [4,2,7,1,3] val = 5 4 2 7 1 3 5 ALGORITHM STEPS 1 Start at Root Compare val(5) with root(4) 2 Go Right (5 > 4) Move to right child (7) 3 Go Left (5 < 7) Left child is null 4 Insert Node Create new node with val=5 Traversal Path: 4 --> 7 --> 5 if (val < node.val) go left else go right insert when null FINAL RESULT Updated BST: 4 2 7 1 3 5 NEW! [4, 2, 7, 1, 3, 5] OK - BST Property Valid 4 < 5 < 7 (correct position) Key Insight: BST insertion always follows a path from root to a leaf position. Compare the value at each node: go left if smaller, go right if larger. Insert at the first null position found. Time: O(h), Space: O(h) TutorialsPoint - Insert into a Binary Search Tree | Optimal BST Insertion
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