this is in java, please help create two classes: a demo class and a class to con
ID: 3572329 • 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
Hi, Please find my implementation.
Please let me know in case of any issue.
##################################################################
/* Class containing left and right child of current
node and key value*/
class Node
{
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
//A Java program to introduce Binary Tree
class BinaryTree
{
// Root of Binary Tree
Node root;
// Constructors
BinaryTree(int key)
{
root = new Node(key);
}
BinaryTree()
{
root = null;
}
public void insert(int key){
if(root == null){
root = new Node(key);
return;
}
insert(root, key);
}
private void insert(Node root, int key){
if(root.left == null){
root.left = new Node(key);
return;
}
if(root.right == null){
root.right = new Node(key);
return;
}
insert(root.left, key);
}
public boolean search(int key){
return search(root, key);
}
private boolean search(Node root, int key){
if(root == null)
return false;
if(root.key == key)
return true;
boolean flag = search(root.left, key);
if(flag)
return true;
else return search(root.right, key);
}
public void preorder(){
preorder(root);
System.out.println();
}
private void preorder(Node root){
if(root == null)
return;
System.out.print(root.key+" ");
preorder(root.left);
preorder(root.right);
}
}
####################### Demo Class ###########################
import java.util.Scanner;
public class BinaryTreeDemo {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
Scanner sc = new Scanner(System.in);
for(int i=1; i<=10; i++){
tree.insert(i);
}
tree.preorder();
System.out.println("Enter key to be search: ");
int key = sc.nextInt();
if(tree.search(key)){
System.out.println("key is present in tree");
}else{
System.out.println("key is not present in tree");
}
}
}
/*
Sample run:
1 2 4 6 8 10 9 7 5 3
Enter key to be search:
10
key is present in tree
1 2 4 6 8 10 9 7 5 3
Enter key to be search:
11
key is not present in tree
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.