SlideShare a Scribd company logo
1 of 10
Download to read offline
There is BinarySearchTree class. When removing a node from a BST, we can replace it with
either its predecessor or its successor. Complete the predecessor() method
so that it returns the node that comes immediately before e. Hint: the work needed to find the
predecessor is a mirror image of what is required to find a node's
successor, so use successor() as a resource.
BinarySearchTree class:
Solution
import java.util.AbstractSet;
import java.util.Iterator;
public class BinarySearchTree> extends AbstractSet {
protected BTNode root;
protected int size;
/**
* Initializes this BinarySearchTree object to be empty, to contain only
* elements of type E, to be ordered by the Comparable interface, and to
* contain no duplicate elements.
*/
public BinarySearchTree() {
root = null;
size = 0;
}
/**
* Initializes this BinarySearchTree object to contain a shallow copy of a
* specified BinarySearchTree object. The worstTime(n) is O(n), where n is the
* number of elements in the specified BinarySearchTree object.
*
* @param otherTree - the specified BinarySearchTree object that this
* BinarySearchTree object will be assigned a shallow copy of.
*/
public BinarySearchTree(BinarySearchTree otherTree) {
root = copy(otherTree.root, null);
size = otherTree.size;
}
protected BTNode copy(BTNode p, BTNode parent) {
if (p != null) {
BTNode q = new BTNode(p.element, parent);
q.left = copy(p.left, q);
q.right = copy(p.right, q);
return q;
}
return null;
} // method copy
/**
* Finds the predecessor of a specified BTNode object in this BinarySearchTree. The
worstTime(n) is O(n) and
* averageTime(n) is constant.
*
* @param e - the BTNode object whose successor is to be found.
* @return the successor of e, if e has a successor; otherwise, return null.
*/
protected BTNode predecessor(BTNode e) {
if (e == null) {
return null;
} else if (e.left != null) {
// successor is leftmost BTNode in right subtree of e
BTNode p = e.left;
while (p.right != null) {
p = p.right;
}
return p;
} // e has a right child
else {
// go up the tree to the right as far as possible, then go up
// to the left.
BTNode p = e.parent;
BTNode ch = e;
while ((p != null) && (ch == p.left)) {
ch = p;
p = p.parent;
} // while
return p;
} // e has no left child
// method successor
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BinarySearchTree)) {
return false;
}
return equals(root, ((BinarySearchTree) obj).root);
} // method 1-parameter equals
public boolean equals(BTNode p, BTNode q) {
if ((p == null) || (q == null)) {
return p == q;
}
if (!p.element.equals(q.element)) {
return false;
}
if (equals(p.left, q.left) && equals(p.right, q.right)) {
return true;
}
return false;
}
/**
* Returns the size of this BinarySearchTree object.
*
* @return the size of this BinarySearchTree object.
*/
@Override
public int size() {
return size;
}
/**
* Iterator method will be implemented for a future
*
* @return an iterator positioned at the smallest element in this
* BinarySearchTree object.
*/
@Override
public Iterator iterator() {
// Skipped in preparation for next week
throw new UnsupportedOperationException("Not implemented yet!");
}
/**
* Determines if there is at least one element in this BinarySearchTree object
* that equals a specified element. The worstTime(n) is O(n) and
* averageTime(n) is O(log n).
*
* @param obj - the element sought in this BinarySearchTree object.
* @return true - if there is an element in this BinarySearchTree object that
* equals obj; otherwise, return false.
* @throws ClassCastException - if obj cannot be compared to the elements in
* this BinarySearchTree object.
* @throws NullPointerException - if obj is null.
*/
@Override
public boolean contains(Object obj) {
return getBTNode(obj) != null;
}
/**
* Ensures that this BinarySearchTree object contains a specified element. The
* worstTime(n) is O(n) and averageTime(n) is O(log n).
*
* @param element - the element whose presence is ensured in this
* BinarySearchTree object.
* @return true - if this BinarySearchTree object changed as a result of this
* method call (that is, if element was actually inserted); otherwise,
* return false.
* @throws ClassCastException - if element cannot be compared to the elements
* already in this BinarySearchTree object.
* @throws NullPointerException - if element is null.
*/
@Override
public boolean add(E element) {
if (root == null) {
if (element == null) {
throw new NullPointerException();
}
root = new BTNode(element, null);
size++ ;
return true;
}
else {
BTNode temp = root;
int comp;
while (true) {
comp = element.compareTo(temp.element);
if (comp == 0) {
return false;
}
if (comp < 0) {
if (temp.left != null) {
temp = temp.left;
} else {
temp.left = new BTNode(element, temp);
size++ ;
return true;
} // temp.left == null
} else if (temp.right != null) {
temp = temp.right;
} else {
temp.right = new BTNode(element, temp);
size++ ;
return true;
} // temp.right == null
} // while
} // root not null
} // method add
/**
* Ensures that this BinarySearchTree object does not contain a specified
* element. The worstTime(n) is O(n) and averageTime(n) is O(log n).
*
* @param obj - the object whose absence is ensured in this BinarySearchTree
* object.
* @return true - if this BinarySearchTree object changed as a result of this
* method call (that is, if obj was actually removed); otherwise,
* return false.
* @throws ClassCastException - if obj cannot be compared to the elements
* already in this BinarySearchTree object.
* @throws NullPointerException - if obj is null.
*/
@Override
public boolean remove(Object obj) {
BTNode e = getBTNode(obj);
if (e == null) {
return false;
}
deleteBTNode(e);
return true;
}
/**
* Finds the BTNode object that houses a specified element, if there is such an BTNode. The
worstTime(n) is O(n), and
* averageTime(n) is O(log n).
*
* @param obj - the element whose BTNode is sought.
* @return the BTNode object that houses obj - if there is such an BTNode; otherwise, return
null.
* @throws ClassCastException - if obj is not comparable to the elements already in this
BinarySearchTree object.
* @throws NullPointerException - if obj is null.
*/
@SuppressWarnings("unchecked")
protected BTNode getBTNode(Object obj) {
int comp;
if (obj == null) {
throw new NullPointerException();
}
if (!(obj instanceof Comparable)) {
return null;
}
Comparable compObj = (Comparable) obj;
BTNode e = root;
while (e != null) {
comp = compObj.compareTo(e.element);
if (comp == 0) {
return e;
} else if (comp < 0) {
e = e.left;
} else {
e = e.right;
}
} // while
return null;
}
/**
* Deletes the element in a specified BTNode object from this BinarySearchTree.
*
* @param p - the BTNode object whose element is to be deleted from this BinarySearchTree
object.
* @return the BTNode object that was actually deleted from this BinarySearchTree object.
*/
protected BTNode deleteBTNode(BTNode p) {
size-- ;
// If p has two children, replace p's element with p's successor's
// element, then make p reference that successor.
if ((p.left != null) && (p.right != null)) {
BTNode s = successor(p);
p.element = s.element;
p = s;
} // p had two children
// At this point, p has either no children or one child.
BTNode replacement;
if (p.left != null) {
replacement = p.left;
} else {
replacement = p.right;
}
// If p has at least one child, link replacement to p.parent.
if (replacement != null) {
replacement.parent = p.parent;
if (p.parent == null) {
root = replacement;
} else if (p == p.parent.left) {
p.parent.left = replacement;
} else {
p.parent.right = replacement;
}
} // p has at least one child
else if (p.parent == null) {
root = null;
} else {
if (p == p.parent.left) {
p.parent.left = null;
} else {
p.parent.right = null;
}
} // p has a parent but no children
return p;
} // method deleteBTNode
/**
* Finds the successor of a specified BTNode object in this BinarySearchTree. The
worstTime(n) is O(n) and
* averageTime(n) is constant.
*
* @param e - the BTNode object whose successor is to be found.
* @return the successor of e, if e has a successor; otherwise, return null.
*/
protected BTNode successor(BTNode e) {
if (e == null) {
return null;
} else if (e.right != null) {
// successor is leftmost BTNode in right subtree of e
BTNode p = e.right;
while (p.left != null) {
p = p.left;
}
return p;
} // e has a right child
else {
// go up the tree to the left as far as possible, then go up
// to the right.
BTNode p = e.parent;
BTNode ch = e;
while ((p != null) && (ch == p.right)) {
ch = p;
p = p.parent;
} // while
return p;
} // e has no right child
} // method successor
protected static class BTNode {
protected E element;
protected BTNode left = null, right = null, parent;
/**
* Initializes this BTNode object. This default constructor is defined for the sake of subclasses
of the
* BinarySearchTree class.
*/
public BTNode() {}
/**
* Initializes this BTNode object from element and parent.
*/
public BTNode(E element, BTNode parent) {
this.element = element;
this.parent = parent;
} // constructor
} // class BTNode
} // class BinarySearchTree

More Related Content

Similar to There is BinarySearchTree class. When removing a node from a BST, we.pdf

import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
deepakangel
 
10 Solution#include-iostream-h- #include-conio-h- #include-process-h-.docx
10 Solution#include-iostream-h- #include-conio-h- #include-process-h-.docx10 Solution#include-iostream-h- #include-conio-h- #include-process-h-.docx
10 Solution#include-iostream-h- #include-conio-h- #include-process-h-.docx
todd991
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
malavshah9013
 
How to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdfHow to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdf
feelingcomputors
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java ---  - Defines the interface to a stack.docxJava Foundations StackADT-java ---  - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
VictorXUQGloverl
 
4. The size of instructions can be fixed or variable. What are advant.pdf
4. The size of instructions can be fixed or variable. What are advant.pdf4. The size of instructions can be fixed or variable. What are advant.pdf
4. The size of instructions can be fixed or variable. What are advant.pdf
mumnesh
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdf
erremmfab
 
In the class LinkedBinarySearchTree implement only the following metho.pdf
In the class LinkedBinarySearchTree implement only the following metho.pdfIn the class LinkedBinarySearchTree implement only the following metho.pdf
In the class LinkedBinarySearchTree implement only the following metho.pdf
sidkucheria
 
On the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdfOn the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdf
wasemanivytreenrco51
 
Note- Can someone help me with the private E get(int index- int curren (1).docx
Note- Can someone help me with the private E get(int index- int curren (1).docxNote- Can someone help me with the private E get(int index- int curren (1).docx
Note- Can someone help me with the private E get(int index- int curren (1).docx
VictorzH8Bondx
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
adityastores21
 
To create a node for a binary search tree (BTNode, ) and to create a .pdf
To create a node for a binary search tree (BTNode, ) and to create a .pdfTo create a node for a binary search tree (BTNode, ) and to create a .pdf
To create a node for a binary search tree (BTNode, ) and to create a .pdf
bhim1213
 
Note- Can someone help me with the Public boolean add(E value) method.pdf
Note- Can someone help me with the Public boolean add(E value) method.pdfNote- Can someone help me with the Public boolean add(E value) method.pdf
Note- Can someone help me with the Public boolean add(E value) method.pdf
Stewart29UReesa
 
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
michardsonkhaicarr37
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
arrowmobile
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
illyasraja7
 
Please complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docxPlease complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docx
cgraciela1
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
ajaycosmeticslg
 
Write a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdfWrite a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdf
hardjasonoco14599
 

Similar to There is BinarySearchTree class. When removing a node from a BST, we.pdf (20)

import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
 
10 Solution#include-iostream-h- #include-conio-h- #include-process-h-.docx
10 Solution#include-iostream-h- #include-conio-h- #include-process-h-.docx10 Solution#include-iostream-h- #include-conio-h- #include-process-h-.docx
10 Solution#include-iostream-h- #include-conio-h- #include-process-h-.docx
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
 
How to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdfHow to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdf
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java ---  - Defines the interface to a stack.docxJava Foundations StackADT-java ---  - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
 
4. The size of instructions can be fixed or variable. What are advant.pdf
4. The size of instructions can be fixed or variable. What are advant.pdf4. The size of instructions can be fixed or variable. What are advant.pdf
4. The size of instructions can be fixed or variable. What are advant.pdf
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdf
 
In the class LinkedBinarySearchTree implement only the following metho.pdf
In the class LinkedBinarySearchTree implement only the following metho.pdfIn the class LinkedBinarySearchTree implement only the following metho.pdf
In the class LinkedBinarySearchTree implement only the following metho.pdf
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
On the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdfOn the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdf
 
Note- Can someone help me with the private E get(int index- int curren (1).docx
Note- Can someone help me with the private E get(int index- int curren (1).docxNote- Can someone help me with the private E get(int index- int curren (1).docx
Note- Can someone help me with the private E get(int index- int curren (1).docx
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
 
To create a node for a binary search tree (BTNode, ) and to create a .pdf
To create a node for a binary search tree (BTNode, ) and to create a .pdfTo create a node for a binary search tree (BTNode, ) and to create a .pdf
To create a node for a binary search tree (BTNode, ) and to create a .pdf
 
Note- Can someone help me with the Public boolean add(E value) method.pdf
Note- Can someone help me with the Public boolean add(E value) method.pdfNote- Can someone help me with the Public boolean add(E value) method.pdf
Note- Can someone help me with the Public boolean add(E value) method.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
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
 
Please complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docxPlease complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docx
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
 
Write a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdfWrite a C++ program that implements a binary search tree (BST) to man.pdf
Write a C++ program that implements a binary search tree (BST) to man.pdf
 

More from Dhanrajsolanki2091

Make drawings of both organisms stained in each staining procedure. L.pdf
Make drawings of both organisms stained in each staining procedure. L.pdfMake drawings of both organisms stained in each staining procedure. L.pdf
Make drawings of both organisms stained in each staining procedure. L.pdf
Dhanrajsolanki2091
 
Java Database Connect Write a program that views, inserts, and u.pdf
Java Database Connect Write a program that views, inserts, and u.pdfJava Database Connect Write a program that views, inserts, and u.pdf
Java Database Connect Write a program that views, inserts, and u.pdf
Dhanrajsolanki2091
 
how does malpractice affect quality of healthcare service What are .pdf
how does malpractice affect quality of healthcare service What are .pdfhow does malpractice affect quality of healthcare service What are .pdf
how does malpractice affect quality of healthcare service What are .pdf
Dhanrajsolanki2091
 
How can critical researchers claim to represent groups to which they.pdf
How can critical researchers claim to represent groups to which they.pdfHow can critical researchers claim to represent groups to which they.pdf
How can critical researchers claim to represent groups to which they.pdf
Dhanrajsolanki2091
 
Discuss Allport’s concept of psychological healthy personality.Des.pdf
Discuss Allport’s concept of psychological healthy personality.Des.pdfDiscuss Allport’s concept of psychological healthy personality.Des.pdf
Discuss Allport’s concept of psychological healthy personality.Des.pdf
Dhanrajsolanki2091
 
Did HBGary’s Aaron Barr have the legal and ethical right to pursue A.pdf
Did HBGary’s Aaron Barr have the legal and ethical right to pursue A.pdfDid HBGary’s Aaron Barr have the legal and ethical right to pursue A.pdf
Did HBGary’s Aaron Barr have the legal and ethical right to pursue A.pdf
Dhanrajsolanki2091
 
Define each of the following terms. Be clear whether it is at develop.pdf
Define each of the following terms. Be clear whether it is at develop.pdfDefine each of the following terms. Be clear whether it is at develop.pdf
Define each of the following terms. Be clear whether it is at develop.pdf
Dhanrajsolanki2091
 
Could anyone please explain how CPS1 and CPS2 are used for reliabili.pdf
Could anyone please explain how CPS1 and CPS2 are used for reliabili.pdfCould anyone please explain how CPS1 and CPS2 are used for reliabili.pdf
Could anyone please explain how CPS1 and CPS2 are used for reliabili.pdf
Dhanrajsolanki2091
 

More from Dhanrajsolanki2091 (20)

Please I need help with this....Please also provide comments in each.pdf
Please I need help with this....Please also provide comments in each.pdfPlease I need help with this....Please also provide comments in each.pdf
Please I need help with this....Please also provide comments in each.pdf
 
Please give me the origin and history on Hassall’s corpusclesSol.pdf
Please give me the origin and history on Hassall’s corpusclesSol.pdfPlease give me the origin and history on Hassall’s corpusclesSol.pdf
Please give me the origin and history on Hassall’s corpusclesSol.pdf
 
OBJ. 2 PE 12-2A Dividing partnership net income Han Lee and Monica An.pdf
OBJ. 2 PE 12-2A Dividing partnership net income Han Lee and Monica An.pdfOBJ. 2 PE 12-2A Dividing partnership net income Han Lee and Monica An.pdf
OBJ. 2 PE 12-2A Dividing partnership net income Han Lee and Monica An.pdf
 
O’Connor says that Aristotelian justice “overcomes misorientation to.pdf
O’Connor says that Aristotelian justice “overcomes misorientation to.pdfO’Connor says that Aristotelian justice “overcomes misorientation to.pdf
O’Connor says that Aristotelian justice “overcomes misorientation to.pdf
 
Let T R^5 rightarrow R^3 be a linear transformation whose null space.pdf
Let T R^5 rightarrow R^3 be a linear transformation whose null space.pdfLet T R^5 rightarrow R^3 be a linear transformation whose null space.pdf
Let T R^5 rightarrow R^3 be a linear transformation whose null space.pdf
 
Make drawings of both organisms stained in each staining procedure. L.pdf
Make drawings of both organisms stained in each staining procedure. L.pdfMake drawings of both organisms stained in each staining procedure. L.pdf
Make drawings of both organisms stained in each staining procedure. L.pdf
 
Link to TextThese selected condensed data are taken from a recent ba.pdf
Link to TextThese selected condensed data are taken from a recent ba.pdfLink to TextThese selected condensed data are taken from a recent ba.pdf
Link to TextThese selected condensed data are taken from a recent ba.pdf
 
Java Database Connect Write a program that views, inserts, and u.pdf
Java Database Connect Write a program that views, inserts, and u.pdfJava Database Connect Write a program that views, inserts, and u.pdf
Java Database Connect Write a program that views, inserts, and u.pdf
 
JUST DO QUESTION 32) You have discussed with the human resource ma.pdf
JUST DO QUESTION 32) You have discussed with the human resource ma.pdfJUST DO QUESTION 32) You have discussed with the human resource ma.pdf
JUST DO QUESTION 32) You have discussed with the human resource ma.pdf
 
Ins struction Use the information that is associated with your name .pdf
Ins struction Use the information that is associated with your name .pdfIns struction Use the information that is associated with your name .pdf
Ins struction Use the information that is associated with your name .pdf
 
I how does double fertilization aid in the survival of land plants o.pdf
I how does double fertilization aid in the survival of land plants o.pdfI how does double fertilization aid in the survival of land plants o.pdf
I how does double fertilization aid in the survival of land plants o.pdf
 
how does malpractice affect quality of healthcare service What are .pdf
how does malpractice affect quality of healthcare service What are .pdfhow does malpractice affect quality of healthcare service What are .pdf
how does malpractice affect quality of healthcare service What are .pdf
 
How can critical researchers claim to represent groups to which they.pdf
How can critical researchers claim to represent groups to which they.pdfHow can critical researchers claim to represent groups to which they.pdf
How can critical researchers claim to represent groups to which they.pdf
 
Discuss Allport’s concept of psychological healthy personality.Des.pdf
Discuss Allport’s concept of psychological healthy personality.Des.pdfDiscuss Allport’s concept of psychological healthy personality.Des.pdf
Discuss Allport’s concept of psychological healthy personality.Des.pdf
 
Earning revenue journal entry is recorded asA Increases assets.pdf
Earning revenue journal entry is recorded asA Increases assets.pdfEarning revenue journal entry is recorded asA Increases assets.pdf
Earning revenue journal entry is recorded asA Increases assets.pdf
 
Discuss why is it important to use logical and physical data flow di.pdf
Discuss why is it important to use logical and physical data flow di.pdfDiscuss why is it important to use logical and physical data flow di.pdf
Discuss why is it important to use logical and physical data flow di.pdf
 
Did HBGary’s Aaron Barr have the legal and ethical right to pursue A.pdf
Did HBGary’s Aaron Barr have the legal and ethical right to pursue A.pdfDid HBGary’s Aaron Barr have the legal and ethical right to pursue A.pdf
Did HBGary’s Aaron Barr have the legal and ethical right to pursue A.pdf
 
Define each of the following terms. Be clear whether it is at develop.pdf
Define each of the following terms. Be clear whether it is at develop.pdfDefine each of the following terms. Be clear whether it is at develop.pdf
Define each of the following terms. Be clear whether it is at develop.pdf
 
Could anyone please explain how CPS1 and CPS2 are used for reliabili.pdf
Could anyone please explain how CPS1 and CPS2 are used for reliabili.pdfCould anyone please explain how CPS1 and CPS2 are used for reliabili.pdf
Could anyone please explain how CPS1 and CPS2 are used for reliabili.pdf
 
Complete the following code by deallocating the memory. Int ptr1; .pdf
Complete the following code by deallocating the memory.  Int ptr1;  .pdfComplete the following code by deallocating the memory.  Int ptr1;  .pdf
Complete the following code by deallocating the memory. Int ptr1; .pdf
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 

There is BinarySearchTree class. When removing a node from a BST, we.pdf

  • 1. There is BinarySearchTree class. When removing a node from a BST, we can replace it with either its predecessor or its successor. Complete the predecessor() method so that it returns the node that comes immediately before e. Hint: the work needed to find the predecessor is a mirror image of what is required to find a node's successor, so use successor() as a resource. BinarySearchTree class: Solution import java.util.AbstractSet; import java.util.Iterator; public class BinarySearchTree> extends AbstractSet { protected BTNode root; protected int size; /** * Initializes this BinarySearchTree object to be empty, to contain only * elements of type E, to be ordered by the Comparable interface, and to * contain no duplicate elements. */ public BinarySearchTree() { root = null; size = 0; } /** * Initializes this BinarySearchTree object to contain a shallow copy of a * specified BinarySearchTree object. The worstTime(n) is O(n), where n is the * number of elements in the specified BinarySearchTree object. * * @param otherTree - the specified BinarySearchTree object that this * BinarySearchTree object will be assigned a shallow copy of. */ public BinarySearchTree(BinarySearchTree otherTree) { root = copy(otherTree.root, null); size = otherTree.size; }
  • 2. protected BTNode copy(BTNode p, BTNode parent) { if (p != null) { BTNode q = new BTNode(p.element, parent); q.left = copy(p.left, q); q.right = copy(p.right, q); return q; } return null; } // method copy /** * Finds the predecessor of a specified BTNode object in this BinarySearchTree. The worstTime(n) is O(n) and * averageTime(n) is constant. * * @param e - the BTNode object whose successor is to be found. * @return the successor of e, if e has a successor; otherwise, return null. */ protected BTNode predecessor(BTNode e) { if (e == null) { return null; } else if (e.left != null) { // successor is leftmost BTNode in right subtree of e BTNode p = e.left; while (p.right != null) { p = p.right; } return p; } // e has a right child else { // go up the tree to the right as far as possible, then go up // to the left. BTNode p = e.parent; BTNode ch = e; while ((p != null) && (ch == p.left)) { ch = p; p = p.parent;
  • 3. } // while return p; } // e has no left child // method successor } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (!(obj instanceof BinarySearchTree)) { return false; } return equals(root, ((BinarySearchTree) obj).root); } // method 1-parameter equals public boolean equals(BTNode p, BTNode q) { if ((p == null) || (q == null)) { return p == q; } if (!p.element.equals(q.element)) { return false; } if (equals(p.left, q.left) && equals(p.right, q.right)) { return true; } return false; } /** * Returns the size of this BinarySearchTree object. * * @return the size of this BinarySearchTree object. */ @Override public int size() { return size; } /** * Iterator method will be implemented for a future
  • 4. * * @return an iterator positioned at the smallest element in this * BinarySearchTree object. */ @Override public Iterator iterator() { // Skipped in preparation for next week throw new UnsupportedOperationException("Not implemented yet!"); } /** * Determines if there is at least one element in this BinarySearchTree object * that equals a specified element. The worstTime(n) is O(n) and * averageTime(n) is O(log n). * * @param obj - the element sought in this BinarySearchTree object. * @return true - if there is an element in this BinarySearchTree object that * equals obj; otherwise, return false. * @throws ClassCastException - if obj cannot be compared to the elements in * this BinarySearchTree object. * @throws NullPointerException - if obj is null. */ @Override public boolean contains(Object obj) { return getBTNode(obj) != null; } /** * Ensures that this BinarySearchTree object contains a specified element. The * worstTime(n) is O(n) and averageTime(n) is O(log n). * * @param element - the element whose presence is ensured in this * BinarySearchTree object. * @return true - if this BinarySearchTree object changed as a result of this * method call (that is, if element was actually inserted); otherwise, * return false. * @throws ClassCastException - if element cannot be compared to the elements * already in this BinarySearchTree object.
  • 5. * @throws NullPointerException - if element is null. */ @Override public boolean add(E element) { if (root == null) { if (element == null) { throw new NullPointerException(); } root = new BTNode(element, null); size++ ; return true; } else { BTNode temp = root; int comp; while (true) { comp = element.compareTo(temp.element); if (comp == 0) { return false; } if (comp < 0) { if (temp.left != null) { temp = temp.left; } else { temp.left = new BTNode(element, temp); size++ ; return true; } // temp.left == null } else if (temp.right != null) { temp = temp.right; } else { temp.right = new BTNode(element, temp); size++ ; return true; } // temp.right == null } // while
  • 6. } // root not null } // method add /** * Ensures that this BinarySearchTree object does not contain a specified * element. The worstTime(n) is O(n) and averageTime(n) is O(log n). * * @param obj - the object whose absence is ensured in this BinarySearchTree * object. * @return true - if this BinarySearchTree object changed as a result of this * method call (that is, if obj was actually removed); otherwise, * return false. * @throws ClassCastException - if obj cannot be compared to the elements * already in this BinarySearchTree object. * @throws NullPointerException - if obj is null. */ @Override public boolean remove(Object obj) { BTNode e = getBTNode(obj); if (e == null) { return false; } deleteBTNode(e); return true; } /** * Finds the BTNode object that houses a specified element, if there is such an BTNode. The worstTime(n) is O(n), and * averageTime(n) is O(log n). * * @param obj - the element whose BTNode is sought. * @return the BTNode object that houses obj - if there is such an BTNode; otherwise, return null. * @throws ClassCastException - if obj is not comparable to the elements already in this BinarySearchTree object. * @throws NullPointerException - if obj is null. */
  • 7. @SuppressWarnings("unchecked") protected BTNode getBTNode(Object obj) { int comp; if (obj == null) { throw new NullPointerException(); } if (!(obj instanceof Comparable)) { return null; } Comparable compObj = (Comparable) obj; BTNode e = root; while (e != null) { comp = compObj.compareTo(e.element); if (comp == 0) { return e; } else if (comp < 0) { e = e.left; } else { e = e.right; } } // while return null; } /** * Deletes the element in a specified BTNode object from this BinarySearchTree. * * @param p - the BTNode object whose element is to be deleted from this BinarySearchTree object. * @return the BTNode object that was actually deleted from this BinarySearchTree object. */ protected BTNode deleteBTNode(BTNode p) { size-- ; // If p has two children, replace p's element with p's successor's // element, then make p reference that successor. if ((p.left != null) && (p.right != null)) { BTNode s = successor(p);
  • 8. p.element = s.element; p = s; } // p had two children // At this point, p has either no children or one child. BTNode replacement; if (p.left != null) { replacement = p.left; } else { replacement = p.right; } // If p has at least one child, link replacement to p.parent. if (replacement != null) { replacement.parent = p.parent; if (p.parent == null) { root = replacement; } else if (p == p.parent.left) { p.parent.left = replacement; } else { p.parent.right = replacement; } } // p has at least one child else if (p.parent == null) { root = null; } else { if (p == p.parent.left) { p.parent.left = null; } else { p.parent.right = null; } } // p has a parent but no children return p; } // method deleteBTNode /** * Finds the successor of a specified BTNode object in this BinarySearchTree. The worstTime(n) is O(n) and * averageTime(n) is constant.
  • 9. * * @param e - the BTNode object whose successor is to be found. * @return the successor of e, if e has a successor; otherwise, return null. */ protected BTNode successor(BTNode e) { if (e == null) { return null; } else if (e.right != null) { // successor is leftmost BTNode in right subtree of e BTNode p = e.right; while (p.left != null) { p = p.left; } return p; } // e has a right child else { // go up the tree to the left as far as possible, then go up // to the right. BTNode p = e.parent; BTNode ch = e; while ((p != null) && (ch == p.right)) { ch = p; p = p.parent; } // while return p; } // e has no right child } // method successor protected static class BTNode { protected E element; protected BTNode left = null, right = null, parent; /** * Initializes this BTNode object. This default constructor is defined for the sake of subclasses of the * BinarySearchTree class. */ public BTNode() {}
  • 10. /** * Initializes this BTNode object from element and parent. */ public BTNode(E element, BTNode parent) { this.element = element; this.parent = parent; } // constructor } // class BTNode } // class BinarySearchTree