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.
Example 1:
Given the following BST and value:
root = [4,2,7,1,3]
val = 5
Insert val
into the BST. One possible result is:
[4,2,7,1,3,5]
Example 2:
Given the following BST and value:
root = [40,20,60,10,30,50,70]
val = 25
Insert val
into the BST. One possible result is:
[40,20,60,10,30,50,70,null,null,25]
Write a function that takes the root of a BST and an integer value as input and returns the root of the BST after inserting the value such that the BST properties are maintained.
A brute force approach to inserting a value into a Binary Search Tree (BST) would involve traversing the tree to find the appropriate location to insert the new node while maintaining the BST properties. This might involve checking each node and comparing the value to be inserted with the node's value.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class InsertIntoBST {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
TreeNode current = root;
while (true) {
if (val < current.val) {
if (current.left == null) {
current.left = new TreeNode(val);
break;
} else {
current = current.left;
}
} else {
if (current.right == null) {
current.right = new TreeNode(val);
break;
} else {
current = current.right;
}
}
}
return root;
}
}
The optimal solution involves the same basic idea but can be expressed more concisely using recursion. The BST properties are still maintained during the insertion process.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class InsertIntoBST {
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;
}
}