this is in java, please help create two classes: a demo class and a class to con
ID: 3572331 • Letter: T
Question
this is in java, please help
create two classes: a demo class and a class to contain the search method that will traverse a binary tree and find a specified value. The demo class should create the binary tree with a minimum of 10 values. You may make this a binary search tree, or just a binary tree (that is to say the values are put into the tree ordered, or not ordered). This should be a complete tree. Create your tree as a linked list, not an array. The demo program will then ask the user to enter a value to search for, and then return a statement indicating if it found it or not. Name the demo file (the file with the main method) TreeSearch.java
Explanation / Answer
public class Node {
Node left;
Node right;
int data;
public Node(int data) {
this.left = null;
this.right = null;
this.data = data;
}
public Node() {
super();
}
}
public class BinarySearchTree {
public void insert(Node root, int data) {
if (root == null) {
root = new Node(data);
} else {
if (root.data > data) {
if (root.left != null) {
insert(root.left, data);
} else {
System.out.println("Element inserted into left of Tree");
root.left = new Node(data);
}
} else {
if (root.right != null) {
insert(root.right, data);
} else {
System.out.println("Element inserted into right of Tree");
root.right = new Node(data);
}
}
}
}
public void search(Node root, int element) {
if (root == null) {
System.out.println("Element not Found");
} else {
if (element == root.data) {
System.out.println("Element is found");
return;
} else if (element < root.data) {
search(root.left, element);
} else if (element >= root.data) {
search(root.right, element);
}
}
}
}
import java.util.Scanner;
public class Demo {
public static void main(String args[]){
Scanner input=new Scanner(System.in);
Node root=new Node();
BinarySearchTree tree=new BinarySearchTree();
tree.insert(root, 10);
tree.insert(root, 23);
tree.insert(root, 15);
tree.insert(root, 30);
tree.insert(root, 45);
tree.insert(root, 33);
tree.insert(root, 8);
System.out.println("***********Searching an element in BST*********");
System.out.println("Please Enter a value to be search");
int number=input.nextInt();
tree.search(root, number);
}
}
Sample Output :
Element inserted into right of Tree
Element inserted into right of Tree
Element inserted into left of Tree
Element inserted into right of Tree
Element inserted into right of Tree
Element inserted into left of Tree
Element inserted into left of Tree
**Searching an element in BST
Please Enter a value to be search
15
Element is found
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.