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. Your task is to insert the new value while maintaining the BST property and return the root of the modified tree.
In a BST, for every node:
- All values in the left subtree are less than the node's value
- All values in the right subtree are greater than the node's value
The problem guarantees that the new value does not already exist in the BST. Since there can be multiple valid insertion points that preserve the BST property, you can return any valid result.
Example: Inserting 5 into a BST with root 4 having left child 2 and right child 7 would result in 5 being placed as the left child of 7.
Input & Output
example_1.py โ Basic Insertion
$
Input:
root = [4,2,7,1,3], val = 5
โบ
Output:
[4,2,7,1,3,5] or [4,2,7,1,3,null,null,null,null,null,null,5]
๐ก Note:
The value 5 is greater than root 4, so we go right to node 7. Since 5 < 7, we go to the left child of 7 (which is null) and insert 5 there. The BST property is maintained.
example_2.py โ Single Node Tree
$
Input:
root = [40,20,60,10,30,50,70], val = 25
โบ
Output:
[40,20,60,10,30,50,70,null,null,25]
๐ก Note:
Starting at 40, 25 < 40 so go left to 20. Since 25 > 20, go right to 30. Since 25 < 30, go left to null position and insert 25 as left child of 30.
example_3.py โ Empty Tree
$
Input:
root = [], val = 5
โบ
Output:
[5]
๐ก Note:
When the tree is empty (root is null), simply create a new node with the given value and return it as the new root.
Constraints
-
The number of nodes in the tree will be in the range
[0, 104] -
-108 <= Node.val <= 108 -
-108 <= val <= 108 - It's guaranteed that val does not exist in the original BST
Visualization
Tap to expand
Understanding the Visualization
1
Enter Theater
Start at the main entrance (root node) with your ticket number
2
Follow Signs
Compare your number with the current section - go left if smaller, right if larger
3
Find Empty Seat
When you reach an empty spot, that's where you sit (insert the new node)
4
Seated
You're now part of the organized seating arrangement (BST structure maintained)
Key Takeaway
๐ฏ Key Insight: BST insertion is like following a treasure map - the BST property acts as directional signs that guide us straight to the insertion point without exploring unnecessary paths!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code