SlideShare a Scribd company logo
1 of 6
Download to read offline
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

Similar to import javautilQueue import javautilLinkedList import .pdf

Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdfinfo750646
 
You can list anything, it doesnt matter. I just want to see code f.pdf
You can list anything, it doesnt matter. I just want to see code f.pdfYou can list anything, it doesnt matter. I just want to see code f.pdf
You can list anything, it doesnt matter. I just want to see code f.pdffashionbigchennai
 
Table.java Huffman code frequency tableimport java.io.;im.docx
 Table.java Huffman code frequency tableimport java.io.;im.docx Table.java Huffman code frequency tableimport java.io.;im.docx
Table.java Huffman code frequency tableimport java.io.;im.docxMARRY7
 
Implement a function TNode copy_tree(TNode t) that creates a copy .pdf
Implement a function TNode copy_tree(TNode t) that creates a copy .pdfImplement a function TNode copy_tree(TNode t) that creates a copy .pdf
Implement a function TNode copy_tree(TNode t) that creates a copy .pdffeetshoemart
 
Link list part 2
Link list part 2Link list part 2
Link list part 2Anaya Zafar
 
1. Add a breadth-first (level-order) traversal function to the binar.pdf
1. Add a breadth-first (level-order) traversal function to the binar.pdf1. Add a breadth-first (level-order) traversal function to the binar.pdf
1. Add a breadth-first (level-order) traversal function to the binar.pdfarjuncp10
 
Here is the following code mentioned in the instructions.pdf
Here is the following code mentioned in the instructions.pdfHere is the following code mentioned in the instructions.pdf
Here is the following code mentioned in the instructions.pdfarbaazrabs
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
It is the main program that implement the min(), max(), floor(), cei.pdf
It is the main program that implement the min(), max(), floor(), cei.pdfIt is the main program that implement the min(), max(), floor(), cei.pdf
It is the main program that implement the min(), max(), floor(), cei.pdfannaindustries
 
Help explain the code with line comments public class CompletedLis.pdf
Help explain the code with line comments public class CompletedLis.pdfHelp explain the code with line comments public class CompletedLis.pdf
Help explain the code with line comments public class CompletedLis.pdfalmonardfans
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfmichardsonkhaicarr37
 
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxDIPESH30
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklistritu1806
 
I keep getting NullPointerExcepetion, can someone help me with spinL.pdf
I keep getting NullPointerExcepetion, can someone help me with spinL.pdfI keep getting NullPointerExcepetion, can someone help me with spinL.pdf
I keep getting NullPointerExcepetion, can someone help me with spinL.pdfarkmuzikllc
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfbermanbeancolungak45
 
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdfC++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdffeelinggift
 
Here is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdfHere is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdfmanjan6
 

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

Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
 
You can list anything, it doesnt matter. I just want to see code f.pdf
You can list anything, it doesnt matter. I just want to see code f.pdfYou can list anything, it doesnt matter. I just want to see code f.pdf
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
 Table.java Huffman code frequency tableimport java.io.;im.docx Table.java Huffman code frequency tableimport java.io.;im.docx
Table.java Huffman code frequency tableimport java.io.;im.docx
 
Implement a function TNode copy_tree(TNode t) that creates a copy .pdf
Implement a function TNode copy_tree(TNode t) that creates a copy .pdfImplement a function TNode copy_tree(TNode t) that creates a copy .pdf
Implement a function TNode copy_tree(TNode t) that creates a copy .pdf
 
Link list part 2
Link list part 2Link list part 2
Link list part 2
 
1. Add a breadth-first (level-order) traversal function to the binar.pdf
1. Add a breadth-first (level-order) traversal function to the binar.pdf1. Add a breadth-first (level-order) traversal function to the binar.pdf
1. Add a breadth-first (level-order) traversal function to the binar.pdf
 
Here is the following code mentioned in the instructions.pdf
Here is the following code mentioned in the instructions.pdfHere is the following code mentioned in the instructions.pdf
Here is the following code mentioned in the instructions.pdf
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
It is the main program that implement the min(), max(), floor(), cei.pdf
It is the main program that implement the min(), max(), floor(), cei.pdfIt is the main program that implement the min(), max(), floor(), cei.pdf
It is the main program that implement the min(), max(), floor(), cei.pdf
 
Help explain the code with line comments public class CompletedLis.pdf
Help explain the code with line comments public class CompletedLis.pdfHelp explain the code with line comments public class CompletedLis.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
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.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
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdf
 
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklist
 
I keep getting NullPointerExcepetion, can someone help me with spinL.pdf
I keep getting NullPointerExcepetion, can someone help me with spinL.pdfI keep getting NullPointerExcepetion, can someone help me with spinL.pdf
I keep getting NullPointerExcepetion, can someone help me with spinL.pdf
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .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
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdfC++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
 
Linked lists
Linked listsLinked lists
Linked lists
 
Sorter
SorterSorter
Sorter
 
Here is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdfHere is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdf
 

More from ADITIEYEWEAR

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

More from ADITIEYEWEAR (20)

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

Recently uploaded

fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 

Recently uploaded (20)

fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 

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.