Untitled
user_0781376
plain_text
8 months ago
3.1 kB
19
Indexable
class Main {
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
Node root;
// Constructor
Main() {
root = null;
}
// Insert a key in BST
void insert(int key) {
root = insertRec(root, key);
}
Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
// Inorder traversal (Left - Root - Right)
void inorder() {
inorderRec(root);
}
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.key + " ");
inorderRec(root.right);
}
}
// Search a key in BST
boolean search(int key) {
return searchRec(root, key) != null;
}
Node searchRec(Node root, int key) {
if (root == null || root.key == key)
return root;
if (key < root.key)
return searchRec(root.left, key);
return searchRec(root.right, key);
}
// Delete a key from BST
void delete(int key) {
root = deleteRec(root, key);
}
Node deleteRec(Node root, int key) {
if (root == null)
return root;
if (key < root.key)
root.left = deleteRec(root.left, key);
else if (key > root.key)
root.right = deleteRec(root.right, key);
else {
// Node with only one child or no child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
// Node with two children: Get inorder successor (smallest in right subtree)
root.key = minValue(root.right);
root.right = deleteRec(root.right, root.key);
}
return root;
}
int minValue(Node root) {
int minv = root.key;
while (root.left != null) {
minv = root.left.key;
root = root.left;
}
return minv;
}
// Driver code
public static void main(String[] args) {
Main tree = new Main();
// Insert nodes
tree.insert(50);
tree.insert(30);
tree.insert(70);
tree.insert(20);
tree.insert(40);
tree.insert(60);
tree.insert(80);
System.out.println("Inorder traversal of the BST:");
tree.inorder();
System.out.println("\n\nSearch 40: " + tree.search(40));
System.out.println("\nDelete 20");
tree.delete(20);
System.out.println("Inorder traversal after deletion:");
tree.inorder();
}
}
Editor is loading...
Leave a Comment