1. Introduction
A Binary Search Tree (BST) is a binary tree where each node has a unique value, and the left subtree of a node contains only nodes with values less than the node’s value, and the right subtree only nodes with values greater than the node’s value. Inserting a new value into a BST involves placing it in the appropriate position based on this ordering to maintain the BST property.
2. Program Steps
1. If the tree is empty, create a new node with the given value and return it.
2. Compare the value to be inserted with the value of the current node.
3. If the value is less than the current node’s value, then move to the left child; otherwise, move to the right child.
4. Repeat step 2 until we find an appropriate position or a null position in the tree.
5. Insert the value at the found position.
3. Code Program
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
left = null;
right = null;
}
}
public class BSTInsertion {
public static TreeNode insert(TreeNode root, int value) {
// If the tree is empty, return a new node
if (root == null) {
return new TreeNode(value);
}
// Otherwise, recur down the tree
if (value < root.value) {
root.left = insert(root.left, value);
} else if (value > root.value) {
root.right = insert(root.right, value);
}
// return the (unchanged) node pointer
return root;
}
public static void levelOrder(TreeNode root) {
if (root == null) return;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode tempNode = queue.poll();
System.out.print(tempNode.value + " ");
if (tempNode.left != null) {
queue.add(tempNode.left);
}
if (tempNode.right != null) {
queue.add(tempNode.right);
}
}
}
public static void main(String[] args) {
TreeNode root = null;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
System.out.println("Level order traversal of the BST after insertion: ");
levelOrder(root);
}
}
Output:
Level order traversal of the BST after insertion: 50 30 70 20 40 60 80
4. Step By Step Explanation
1. The TreeNode class provides the structure for individual nodes in the BST, with attributes for value, left child, and right child.
2. The insert function is a recursive method that helps to position a new value into the BST based on the given rules.
3. When the value is less than the current node's value, we move to the left subtree, and when greater, we move to the right subtree.
4. The process continues recursively until we find the correct position (a null spot) in the tree for the new value.
5. We've also provided a levelOrder function to print the tree in level order, which helps to verify the insertion process visually.
6. The main method demonstrates inserting several values into the BST and then printing it.