0% found this document useful (0 votes)
11 views2 pages

Lab 2

Uploaded by

sgkonneh131
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Lab 2

Uploaded by

sgkonneh131
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

class TreeNode {

int value;
TreeNode left, right;

TreeNode(int value) {
this.value = value;
this.left = this.right = null;
}
}

class BinarySearchTree {
private TreeNode root;

public void insert(int value) {


root = insertRec(root, value);
}

private TreeNode insertRec(TreeNode root, int value) {


if (root == null) {
root = new TreeNode(value);
return root;
}
if (value < root.value)
root.left = insertRec(root.left, value);
else if (value > root.value)
root.right = insertRec(root.right, value);
return root;
}

public void delete(int value) {


root = deleteRec(root, value);
}

private TreeNode deleteRec(TreeNode root, int value) {


if (root == null) return root;
if (value < root.value)
root.left = deleteRec(root.left, value);
else if (value > root.value)
root.right = deleteRec(root.right, value);
else {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
root.value = minValue(root.right);
root.right = deleteRec(root.right, root.value);
}
return root;
}

private int minValue(TreeNode root) {


int minValue = root.value;
while (root.left != null) {
root = root.left;
minValue = root.value;
}
return minValue;
}

public boolean search(int value) {


return searchRec(root, value) != null;
}

private TreeNode searchRec(TreeNode root, int value) {


if (root == null || root.value == value)
return root;
if (root.value > value)
return searchRec(root.left, value);
return searchRec(root.right, value);
}

public void inOrderTraversal() {


inOrderRec(root);
System.out.println();
}

private void inOrderRec(TreeNode root) {


if (root != null) {
inOrderRec(root.left);
System.out.print(root.value + " ");
inOrderRec(root.right);
}
}

public static void main(String[] args) {


BinarySearchTree bst = new BinarySearchTree();
bst.insert(50);
bst.insert(30);
bst.insert(20);
bst.insert(40);
bst.insert(70);
bst.insert(60);
bst.insert(80);
bst.inOrderTraversal(); // 20 30 40 50 60 70 80
bst.delete(20);
bst.inOrderTraversal(); // 30 40 50 60 70 80
System.out.println(bst.search(40)); // true
System.out.println(bst.search(100)); // false
}
}

You might also like