SE214 - Lab8 - Fall2024.pdf by Karam
SE214 - Lab8 - Fall2024.pdf by Karam
Objectives:
A. Write BinarySearchTree Class which has attribute “root” and have following methods:
1. Zero argument constructors
2. Find a method that takes an integer and returns true, if the integer is found in a tree.
3. Insert method that inserts the integer into its right place.
4. isEmpty method to see if a tree is empty.
5. Display method that displays the tree. You can display the tree as left, root, right.
6. Minimum method that searches for the smallest node in tree and return its data.
7. Maximum method that searches for the biggest node in tree and return its data.
8. Delete method that deletes a node with specific value.
B. Write a main test class for testing all the methods implemented in part A.
public class Node {
int data;
Node left,right;
// Test isEmpty
System.out.println("Is tree empty? " + bst.isEmpty());
// Insert values
bst.insert(10);
bst.insert(5);
bst.insert(15);
bst.insert(3);
bst.insert(7);
bst.insert(12);
bst.insert(18);
// Test display
System.out.print("Tree elements in order: ");
bst.display();
// Test find method
System.out.println("Find 7: " + bst.find(7));
System.out.println("Find 20: " + bst.find(20));
A. Write a class Tree which has attribute “root” and have following methods:
B. Write a main test class for testing all the methods implemented in part A using the following tree.
Inorder traversal visits the node in the order: Left -> Root -> Right
Preorder traversal visits the node in the order: Root -> Left -> Right
Postorder traversal visits the node in the order: Left -> Right -> Root
Node(int data) {
this.data = data;
left = right = null;
}
}
// Pre-order traversal
public void preOrder() {
System.out.print("Pre-order: ");
preOrderRec(root);
System.out.println();
}
// In-order traversal
public void inOrder() {
System.out.print("In-order: ");
inOrderRec(root);
System.out.println();
}
// Post-order traversal
public void postOrder() {
System.out.print("Post-order: ");
postOrderRec(root);
System.out.println();
}
myTree.insert(1);
myTree.insert(2);
myTree.insert(3);
myTree.insert(4);
myTree.insert(5);
myTree.insert(6);
myTree.insert(7);
myTree.insert(8);
myTree.insert(9);
// Display traversals
myTree.preOrder(); // Expected: 10 5 3 7 15 12 18
myTree.inOrder(); // Expected: 3 5 7 10 12 15 18
myTree.postOrder();
}
Sample Output: