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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code