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
To create a node for a binary search tree (BTNode, ) and to create a .pdf
bhim1213
 
PDF
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
shaktisinhgandhinaga
 
PDF
A perfect left-sided binary tree is a binary tree where every intern.pdf
michardsonkhaicarr37
 
PDF
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
info750646
 
DOCX
For this project, write a program that stores integers in a binary.docx
budbarber38650
 
DOCX
Required to augment the authors Binary Search Tree (BST) code to .docx
debishakespeare
 
PDF
1)(JAVA) Extend the Binary Search Tree ADT to include a public metho.pdf
petercoiffeur18
 
PPT
Unit14_BinarySearchTree.ppt
plagcheck
 
To create a node for a binary search tree (BTNode, ) and to create a .pdf
bhim1213
 
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
shaktisinhgandhinaga
 
A perfect left-sided binary tree is a binary tree where every intern.pdf
michardsonkhaicarr37
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
info750646
 
For this project, write a program that stores integers in a binary.docx
budbarber38650
 
Required to augment the authors Binary Search Tree (BST) code to .docx
debishakespeare
 
1)(JAVA) Extend the Binary Search Tree ADT to include a public metho.pdf
petercoiffeur18
 
Unit14_BinarySearchTree.ppt
plagcheck
 

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

PDF
BSTNode.Java Node class used for implementing the BST. .pdf
info189835
 
PDF
For the code below complete the preOrder() method so that it perform.pdf
xlynettalampleyxc
 
PDF
JavaCreate a java application using the code example in the follo.pdf
ambersushil
 
PDF
Create an implementation of a binary tree using the recursive appr.pdf
federaleyecare
 
PPTX
B+ trees and height balance tree
Jasleen Kaur (Chandigarh University)
 
PDF
Given the following codepackage data1;import java.util.;p.pdf
illyasraja7
 
PDF
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
shyamsunder1211
 
PDF
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Footageetoffe16
 
PDF
There is BinarySearchTree class. When removing a node from a BST, we.pdf
Dhanrajsolanki2091
 
PDF
package DataStructures; public class HelloWorld AnyType extends.pdf
apleathers
 
PPTX
B+ trees - Insertion, Deletion
PreethiSureshkumar1
 
PPT
s11_bin_search_trees.ppt
DrKishoreVermaS1
 
PPT
BINARY SEARCH TREE
ER Punit Jain
 
DOCX
Once you have all the structures working as intended- it is time to co.docx
farrahkur54
 
DOCX
Please finish everything marked TODO BinaryNode-java public class Bi.docx
JakeT2gGrayp
 
PDF
Generics and data structures in Java for an introductory programming course
ZiyanMaraikar1
 
PDF
in this assignment you are asked to write a simple driver program an.pdf
michardsonkhaicarr37
 
PDF
How to do the main method for this programBinaryNode.javapublic.pdf
feelingcomputors
 
PDF
Tree Leetcode - Interview Questions - Easy Collections
Sunil Yadav
 
PPTX
datastructurestreeand type of trees.pptx
Muhammad439928
 
BSTNode.Java Node class used for implementing the BST. .pdf
info189835
 
For the code below complete the preOrder() method so that it perform.pdf
xlynettalampleyxc
 
JavaCreate a java application using the code example in the follo.pdf
ambersushil
 
Create an implementation of a binary tree using the recursive appr.pdf
federaleyecare
 
B+ trees and height balance tree
Jasleen Kaur (Chandigarh University)
 
Given the following codepackage data1;import java.util.;p.pdf
illyasraja7
 
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
shyamsunder1211
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Footageetoffe16
 
There is BinarySearchTree class. When removing a node from a BST, we.pdf
Dhanrajsolanki2091
 
package DataStructures; public class HelloWorld AnyType extends.pdf
apleathers
 
B+ trees - Insertion, Deletion
PreethiSureshkumar1
 
s11_bin_search_trees.ppt
DrKishoreVermaS1
 
BINARY SEARCH TREE
ER Punit Jain
 
Once you have all the structures working as intended- it is time to co.docx
farrahkur54
 
Please finish everything marked TODO BinaryNode-java public class Bi.docx
JakeT2gGrayp
 
Generics and data structures in Java for an introductory programming course
ZiyanMaraikar1
 
in this assignment you are asked to write a simple driver program an.pdf
michardsonkhaicarr37
 
How to do the main method for this programBinaryNode.javapublic.pdf
feelingcomputors
 
Tree Leetcode - Interview Questions - Easy Collections
Sunil Yadav
 
datastructurestreeand type of trees.pptx
Muhammad439928
 

More from ADITIEYEWEAR (20)

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

Recently uploaded (20)

PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PPTX
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
PPTX
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPTX
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
Basics and rules of probability with real-life uses
ravatkaran694
 

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.