SlideShare a Scribd company logo
import java.util.Queue;
import java.util.LinkedList;
import java.util.NoSuchElementException;
public class BinaryTree<T extends Comparable<T>> {
BTNode root;
public BinaryTree() {
root = null;
}
public BinaryTree(BTNode root) {
root = null;
}
public void purge(){
root = null;
}
public boolean isEmpty(){
return root == null;
}
public void insert(T key){
if (root == null) {
root = new BTNode(key);
return;
}
BTNode temp;
Queue<BTNode> q = new LinkedList<BTNode>();
q.add(root);
// Do level order traversal until we find the first empty left or right child.
while (!q.isEmpty()) {
temp = q.poll();
if (temp.left == null) {
temp.left = new BTNode(key);
break;
}
else
q.add(temp.left);
if (temp.right == null) {
temp.right = new BTNode(key);
break;
}
else
q.add(temp.right);
}
}
// delete by copying last node
public void deleteByCopying(T data){
if(root == null)
throw new UnsupportedOperationException("Tree is empty!");
else if(root.left == null && root.right == null){
if(root.data.equals(data))
root = null;
else
throw new NoSuchElementException(data + " not in the tree.");
return;
}
Queue<BTNode> queue = new LinkedList<BTNode>();
queue.add(root);
BTNode keyNode = null;
BTNode currentNode = null;
BTNode parentNode = root;
boolean found = false;
while(! queue.isEmpty()){
currentNode = queue.poll();
if(currentNode.data.equals(data)){
if(! found){
keyNode = currentNode;
found = true;
}
}
if(currentNode.left != null){
queue.add(currentNode.left);
parentNode = currentNode;
}
if(currentNode.right != null){
queue.add(currentNode.right);
parentNode = currentNode;
}
}
if(! found)
throw new NoSuchElementException(data + " not in tree.");
while(! queue.isEmpty()){
currentNode = queue.poll();
System.out.print(currentNode.data + " ");
if(currentNode.left != null){
queue.add(currentNode.left);
parentNode = currentNode;
}
if(currentNode.right != null){
queue.add(currentNode.right);
parentNode = currentNode;
}
}
keyNode.data = currentNode.data;
if(parentNode.left == currentNode)
parentNode.left = null;
else if(parentNode.right == currentNode)
parentNode.right = null;
}
public void levelOrderTraversal(){ // BreadthFirstTraversal
levelOrderTraversal(root);
}
// BreadthFirst Traversal
protected void levelOrderTraversal(BTNode root){
if(root == null)
return;
Queue<BTNode> queue = new LinkedList<BTNode>();
BTNode node = root;
queue.add(node);
while(! queue.isEmpty()){
node = queue.poll();
visit(node);
if(node.left != null)
queue.add(node.left);
if(node.right != null)
queue.add(node.right);
}
}
public void levelOrderTraversalByLevels(){
levelOrderTraversalByLevels(root);
}
protected void levelOrderTraversalByLevels(BTNode<T> root){
Queue q = new LinkedList();
int levelNodes = 0;
if(root==null)
return;
q.add(root);
while(!q.isEmpty()){
levelNodes = q.size();
while(levelNodes>0){
BTNode n = (BTNode)q.remove();
System.out.print(" " + n.data);
if(n.left!=null)
q.add(n.left);
if(n.right!=null)
q.add(n.right);
levelNodes--;
}
System.out.println("");
}
}
protected void visit(BTNode<T> p) {
System.out.print(p.data + " ");
}
public void inorderTraversal(){
inorderTraversal(root);
}
protected void inorderTraversal(BTNode node) {
if (node == null)
return;
inorderTraversal(node.left);
visit(node);
inorderTraversal(node.right);
}
public void postorderTraversal(){
postorderTraversal(root);
}
protected void postorderTraversal(BTNode node){
if (node == null)
return;
postorderTraversal(node.left);
postorderTraversal(node.right);
visit(node);
}
public void preorderTraversal(){
preorderTraversal(root);
}
protected void preorderTraversal(BTNode node){
if (node == null)
return;
visit(node);
preorderTraversal(node.left);
preorderTraversal(node.right);
}
public boolean search(T key){
if(root == null)
return false;
Queue<BTNode> queue = new LinkedList<BTNode>();
BTNode node = root;
queue.add(node);
while(! queue.isEmpty()){
node = queue.poll();
if(key.equals(node.data))
return true;
if(node.left != null)
queue.add(node.left);
if(node.right != null)
queue.add(node.right);
}
return false;
}
public void printTree(){
printTree(root, "", true);
}
// Print the binary tree
protected void printTree(BTNode currPtr, String indent, boolean last) {
if(indent.equals(""))
System.out.print("t");
if (currPtr != null) {
System.out.print(indent);
if (last) {
System.out.print("R----");
indent += " ";
} else {
System.out.print("L----");
indent += "| ";
}
System.out.println(currPtr.data);
printTree(currPtr.left, indent, false);
printTree(currPtr.right, indent, true);
}
}
//******************************************************************************
}
Given the information and the code above, using Java solve this task:
(Please make sure that the method is boolean not int)
BinaryTree insertion and deletion There are no fixed rules for inserting and deleting from a Binary-
tree. In our Binary-tree implementation, we use the insertion and deletion algorithms given below: -
Given a binary tree and a key, insert the key into the binary tree at the first position available in
level order traversal. Note: We can create a Binary tree without using the insert method. We do
this by creating the root node and then linking it with other nodes: BinaryTree> tree = new
BinaryTree Integer >(); BTNode node1 = new BTNode (7); BTNode node2 = new BTNode (4);
BTNode node 3= new BTNode (28); tree.root = node 1 node1.left = node 2; node2.right = node3; -
Given a binary tree, delete a node from it by making sure that tree shrinks from the bottom (i.e. the
deleted node is replaced by the last leaf node).Lab Tasks 1. Write a recursive instance method
public boolean subtreesHaveEqualNumberofNodes() of the BinaryTree <T> class that returns true
if the invoking Binary T ree <T> object has an equal number of nodes in its left and right subtrees.
Your method must throw java.lang.UnsupportedOperationException if the invoking tree is empty.

More Related Content

PDF
Given the following codepackage data1;import java.util.;p.pdf
PDF
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
PDF
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
PDF
package DataStructures; public class HelloWorld AnyType extends.pdf
PDF
I need help finishing this code in JavaYou will need to create t.pdf
DOC
Ds 2 cycle
PDF
In C++Write a recursive function to determine whether or not a Lin.pdf
PPT
dynamicList.ppt
Given the following codepackage data1;import java.util.;p.pdf
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
package DataStructures; public class HelloWorld AnyType extends.pdf
I need help finishing this code in JavaYou will need to create t.pdf
Ds 2 cycle
In C++Write a recursive function to determine whether or not a Lin.pdf
dynamicList.ppt

Similar to import javautilQueue import javautilLinkedList import .pdf (20)

PDF
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
PDF
Generics and data structures in Java for an introductory programming course
PDF
You can list anything, it doesnt matter. I just want to see code f.pdf
DOCX
Table.java Huffman code frequency tableimport java.io.;im.docx
PDF
Implement a function TNode copy_tree(TNode t) that creates a copy .pdf
PPT
Link list part 2
PDF
1. Add a breadth-first (level-order) traversal function to the binar.pdf
PDF
Here is the following code mentioned in the instructions.pdf
PDF
6. Generics. Collections. Streams
PDF
It is the main program that implement the min(), max(), floor(), cei.pdf
PDF
Help explain the code with line comments public class CompletedLis.pdf
PDF
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
PDF
A perfect left-sided binary tree is a binary tree where every intern.pdf
DOCX
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
PPT
Doublylinklist
PDF
I keep getting NullPointerExcepetion, can someone help me with spinL.pdf
PDF
I want help in the following C++ programming task. Please do coding .pdf
PDF
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
DOCX
Linked lists
RTF
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Generics and data structures in Java for an introductory programming course
You can list anything, it doesnt matter. I just want to see code f.pdf
Table.java Huffman code frequency tableimport java.io.;im.docx
Implement a function TNode copy_tree(TNode t) that creates a copy .pdf
Link list part 2
1. Add a breadth-first (level-order) traversal function to the binar.pdf
Here is the following code mentioned in the instructions.pdf
6. Generics. Collections. Streams
It is the main program that implement the min(), max(), floor(), cei.pdf
Help explain the code with line comments public class CompletedLis.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdf
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
Doublylinklist
I keep getting NullPointerExcepetion, can someone help me with spinL.pdf
I want help in the following C++ programming task. Please do coding .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
Linked lists

More from ADITIEYEWEAR (20)

PDF
In a study on the retirement savings plans of young Canadian.pdf
PDF
In a spreadsheet decompose the change in the debt ratio fro.pdf
PDF
In a school there are 5 sections of 10th standard with same.pdf
PDF
In a recent year grade 10 Washington State public school st.pdf
PDF
In a recent poll the Gallup Organization found that 45 of.pdf
PDF
In a random sample of UTC students 50 indicated they are b.pdf
PDF
In a previous yeac the weights of the members of the San Fra.pdf
PDF
In a questionnaire for 100 pernens the gender distribution .pdf
PDF
In a normal distribution what is the probability that a ran.pdf
PDF
In 2019 scientists conducted a research study about spicy f.pdf
PDF
In a holiday gathering two families family 1 and family 2 .pdf
PDF
in 2019 facebook Announced is Plan 70 pon out a nea stablec.pdf
PDF
In a city of half a million there are initially 400 cases o.pdf
PDF
In a 10year graph with an explanation of Idaho Panhandle H.pdf
PDF
In 2D let xx1x2 Write down the explicit cubic feature.pdf
PDF
In 2018 Tirana Trucks had a retum on equity of 180 and a.pdf
PDF
In 2021 California passed a law to provide all public schoo.pdf
PDF
import yfinance as yf yfTickerstickersAAPL TSLA.pdf
PDF
In 2020 Natural Selection a nationwide computer dating se.pdf
PDF
In 2017 Americans spent a recordhigh 91 billion on Hallo.pdf
In a study on the retirement savings plans of young Canadian.pdf
In a spreadsheet decompose the change in the debt ratio fro.pdf
In a school there are 5 sections of 10th standard with same.pdf
In a recent year grade 10 Washington State public school st.pdf
In a recent poll the Gallup Organization found that 45 of.pdf
In a random sample of UTC students 50 indicated they are b.pdf
In a previous yeac the weights of the members of the San Fra.pdf
In a questionnaire for 100 pernens the gender distribution .pdf
In a normal distribution what is the probability that a ran.pdf
In 2019 scientists conducted a research study about spicy f.pdf
In a holiday gathering two families family 1 and family 2 .pdf
in 2019 facebook Announced is Plan 70 pon out a nea stablec.pdf
In a city of half a million there are initially 400 cases o.pdf
In a 10year graph with an explanation of Idaho Panhandle H.pdf
In 2D let xx1x2 Write down the explicit cubic feature.pdf
In 2018 Tirana Trucks had a retum on equity of 180 and a.pdf
In 2021 California passed a law to provide all public schoo.pdf
import yfinance as yf yfTickerstickersAAPL TSLA.pdf
In 2020 Natural Selection a nationwide computer dating se.pdf
In 2017 Americans spent a recordhigh 91 billion on Hallo.pdf

Recently uploaded (20)

PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Introduction to Building Materials
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PPTX
Cell Types and Its function , kingdom of life
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
1_English_Language_Set_2.pdf probationary
PDF
Empowerment Technology for Senior High School Guide
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Paper A Mock Exam 9_ Attempt review.pdf.
UNIT III MENTAL HEALTH NURSING ASSESSMENT
Chinmaya Tiranga quiz Grand Finale.pdf
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Final Presentation General Medicine 03-08-2024.pptx
Computing-Curriculum for Schools in Ghana
Introduction to Building Materials
Final Presentation General Medicine 03-08-2024.pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
LDMMIA Reiki Yoga Finals Review Spring Summer
A powerpoint presentation on the Revised K-10 Science Shaping Paper
Cell Types and Its function , kingdom of life
History, Philosophy and sociology of education (1).pptx
1_English_Language_Set_2.pdf probationary
Empowerment Technology for Senior High School Guide
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
Practical Manual AGRO-233 Principles and Practices of Natural Farming

import javautilQueue import javautilLinkedList import .pdf

  • 1. import java.util.Queue; import java.util.LinkedList; import java.util.NoSuchElementException; public class BinaryTree<T extends Comparable<T>> { BTNode root; public BinaryTree() { root = null; } public BinaryTree(BTNode root) { root = null; } public void purge(){ root = null; } public boolean isEmpty(){ return root == null; } public void insert(T key){ if (root == null) { root = new BTNode(key); return; } BTNode temp; Queue<BTNode> q = new LinkedList<BTNode>(); q.add(root); // Do level order traversal until we find the first empty left or right child. while (!q.isEmpty()) { temp = q.poll(); if (temp.left == null) { temp.left = new BTNode(key); break; } else q.add(temp.left); if (temp.right == null) { temp.right = new BTNode(key); break; } else q.add(temp.right); } }
  • 2. // delete by copying last node public void deleteByCopying(T data){ if(root == null) throw new UnsupportedOperationException("Tree is empty!"); else if(root.left == null && root.right == null){ if(root.data.equals(data)) root = null; else throw new NoSuchElementException(data + " not in the tree."); return; } Queue<BTNode> queue = new LinkedList<BTNode>(); queue.add(root); BTNode keyNode = null; BTNode currentNode = null; BTNode parentNode = root; boolean found = false; while(! queue.isEmpty()){ currentNode = queue.poll(); if(currentNode.data.equals(data)){ if(! found){ keyNode = currentNode; found = true; } } if(currentNode.left != null){ queue.add(currentNode.left); parentNode = currentNode; } if(currentNode.right != null){ queue.add(currentNode.right); parentNode = currentNode; } } if(! found) throw new NoSuchElementException(data + " not in tree."); while(! queue.isEmpty()){ currentNode = queue.poll(); System.out.print(currentNode.data + " "); if(currentNode.left != null){ queue.add(currentNode.left); parentNode = currentNode;
  • 3. } if(currentNode.right != null){ queue.add(currentNode.right); parentNode = currentNode; } } keyNode.data = currentNode.data; if(parentNode.left == currentNode) parentNode.left = null; else if(parentNode.right == currentNode) parentNode.right = null; } public void levelOrderTraversal(){ // BreadthFirstTraversal levelOrderTraversal(root); } // BreadthFirst Traversal protected void levelOrderTraversal(BTNode root){ if(root == null) return; Queue<BTNode> queue = new LinkedList<BTNode>(); BTNode node = root; queue.add(node); while(! queue.isEmpty()){ node = queue.poll(); visit(node); if(node.left != null) queue.add(node.left); if(node.right != null) queue.add(node.right); } } public void levelOrderTraversalByLevels(){ levelOrderTraversalByLevels(root); } protected void levelOrderTraversalByLevels(BTNode<T> root){ Queue q = new LinkedList(); int levelNodes = 0; if(root==null) return; q.add(root); while(!q.isEmpty()){ levelNodes = q.size();
  • 4. while(levelNodes>0){ BTNode n = (BTNode)q.remove(); System.out.print(" " + n.data); if(n.left!=null) q.add(n.left); if(n.right!=null) q.add(n.right); levelNodes--; } System.out.println(""); } } protected void visit(BTNode<T> p) { System.out.print(p.data + " "); } public void inorderTraversal(){ inorderTraversal(root); } protected void inorderTraversal(BTNode node) { if (node == null) return; inorderTraversal(node.left); visit(node); inorderTraversal(node.right); } public void postorderTraversal(){ postorderTraversal(root); } protected void postorderTraversal(BTNode node){ if (node == null) return; postorderTraversal(node.left); postorderTraversal(node.right); visit(node); } public void preorderTraversal(){ preorderTraversal(root); } protected void preorderTraversal(BTNode node){ if (node == null) return; visit(node);
  • 5. preorderTraversal(node.left); preorderTraversal(node.right); } public boolean search(T key){ if(root == null) return false; Queue<BTNode> queue = new LinkedList<BTNode>(); BTNode node = root; queue.add(node); while(! queue.isEmpty()){ node = queue.poll(); if(key.equals(node.data)) return true; if(node.left != null) queue.add(node.left); if(node.right != null) queue.add(node.right); } return false; } public void printTree(){ printTree(root, "", true); } // Print the binary tree protected void printTree(BTNode currPtr, String indent, boolean last) { if(indent.equals("")) System.out.print("t"); if (currPtr != null) { System.out.print(indent); if (last) { System.out.print("R----"); indent += " "; } else { System.out.print("L----"); indent += "| "; } System.out.println(currPtr.data); printTree(currPtr.left, indent, false); printTree(currPtr.right, indent, true); } } //******************************************************************************
  • 6. } Given the information and the code above, using Java solve this task: (Please make sure that the method is boolean not int) BinaryTree insertion and deletion There are no fixed rules for inserting and deleting from a Binary- tree. In our Binary-tree implementation, we use the insertion and deletion algorithms given below: - Given a binary tree and a key, insert the key into the binary tree at the first position available in level order traversal. Note: We can create a Binary tree without using the insert method. We do this by creating the root node and then linking it with other nodes: BinaryTree> tree = new BinaryTree Integer >(); BTNode node1 = new BTNode (7); BTNode node2 = new BTNode (4); BTNode node 3= new BTNode (28); tree.root = node 1 node1.left = node 2; node2.right = node3; - Given a binary tree, delete a node from it by making sure that tree shrinks from the bottom (i.e. the deleted node is replaced by the last leaf node).Lab Tasks 1. Write a recursive instance method public boolean subtreesHaveEqualNumberofNodes() of the BinaryTree <T> class that returns true if the invoking Binary T ree <T> object has an equal number of nodes in its left and right subtrees. Your method must throw java.lang.UnsupportedOperationException if the invoking tree is empty.