The Given code is: public class BinarySearchTree { public static Node root; publ
ID: 3845583 • Letter: T
Question
The Given code is:
public class BinarySearchTree {
public static Node root;
public static void main(String[] args){
root = new Root(5);
System.out.println(root);
}
public BinarySearchTree(){ // Constructor
this.root = null;
}
public boolean search(int id){
Node current = root;
while(current!=null){
if(current.key==id){
return true;
}else if(current.key>id){
current = current.left;
}else{
current = current.right;
}
}
return false;
}
public void insert(int id){
}
public double height(){ // Compute the height of Binary Search
}
}
public class Node{
int key;
Node left;
Node right;
public Node(int data){
key = data;
left = null;
right = null;
}
}
Explanation / Answer
public class BinarySearchTree {
public static Node root;
public static void main(String[] args){
//root = new Node(5);
BinarySearchTree bs=new BinarySearchTree();
System.out.println("Inserting node 2 1 8");
bs.insert(2);
bs.insert(1);
bs.insert(8);
System.out.println("Height of BST is "+bs.height());
if(bs.search(1))
System.out.println("Element 1 found");
else
System.out.println("Element 1 not found");
if(bs.search(10))
System.out.println("Element 10 found");
else
System.out.println("Element 10 not found");
}
public BinarySearchTree(){ // Constructor
this.root = null;
}
public boolean search(int id){
Node current = root;
while(current!=null){
if(current.key==id){
return true;
}else if(current.key>id){
current = current.left;
}else{
current = current.right;
}
}
return false;
}
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;
}
public void insert(int id){
root = insertRec(root, id);
}
double computeHeight(Node node)
{
if (node == null)
return 0;
else
{
/* compute the depth of each subtree */
double lDepth = computeHeight(node.left);
double rDepth = computeHeight(node.right);
/* use the larger one */
if (lDepth > rDepth)
return (lDepth + 1);
else
return (rDepth + 1);
}
}
public double height(){ // Compute the height of Binary Search
return computeHeight(root);
}
}
============================================================================
Output:(eclipse)
Inserting node 2 1 8
Height of BST is 2.0
Element 1 found
Element 10 not found
==============================================================
.Let me know if you have any problem
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.