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 that 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.
For example, consider the following BST:
4
/ \
2 7
/ \
1 3
If we want to insert the value 5
, the resulting BST could look like this:
4
/ \
2 7
/ \ /
1 3 5
Or like this:
4
/ \
2 7
/ \ \
1 3 5
Write a function that takes the root of a BST and a value to insert, and returns the root of the modified BST after the insertion. The function must maintain the BST property after the insertion.
Constraints:
[0, 10^4]
.-10^8 <= Node.val <= 10^8
Node.val
are unique.-10^8 <= val <= 10^8
val
does not exist in the original BST.A simple, but not necessarily the most efficient, way to insert a value into a BST is to recursively traverse the tree until we find the appropriate place to insert the new node. At each node, we check if the value to insert is less than or greater than the current node's value. If it's less, we move to the left subtree; otherwise, we move to the right subtree. When we reach a null node (an empty spot), we create a new node with the given value and insert it there.
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;
}
}
An iterative approach avoids the overhead of the recursive call stack and can be slightly more efficient in practice. The logic remains the same: traverse the tree, comparing the value to insert with each node's value until an appropriate insertion point (a null node) is found.
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
TreeNode current = root;
TreeNode parent = null;
while (current != null) {
parent = current;
if (val < current.val) {
current = current.left;
} else {
current = current.right;
}
}
if (val < parent.val) {
parent.left = new TreeNode(val);
} else {
parent.right = new TreeNode(val);
}
return root;
}
}
null
, we simply create a new node with the given value and return it as the new root. Both the recursive and iterative solutions handle this case correctly.