Coding Assignment 3
CSC 330: Advanced Data Structures, Spring 2019
Released Monday, April 15, 2019
Due on Canvas on Wednesday, May 1, at 11:59pm
Overview
In this assignment, you’ll implement another variant of a
height-balancing tree known as a
splay tree. The assignment will also give you an opportunity to
work with Java inheritance;
in particular, the base code that you’ll amend is structured so
that your SplayTree class
extends from an abstract class called HeightBalancingTree,
which gives a general template
for how a height-balancing tree should be defined.
As always, please carefully read the entire write-up before you
begin coding your submission.
Splay Trees
As mentioned above, a splay tree is another example of a
height-balancing tree — a binary
search tree that, upon either an insertion or deletion, modifies
the tree through a sequence
of rotations in order to reduce the overall height of the tree.
However, splay trees differ from the other height-balancing
trees we’ve seen (AVL trees,
red-black trees) in terms of the type of guarantees that they
provide. In particular, recall
that both AVL trees and red-black trees maintain the property
that after any insertion or
deletion, the height of the tree is O(log n), where n is the
number of elements in the tree.
Splay trees unfortunately do not provide this (fairly strong)
guarantee; namely, it is possible
for the height of a splay tree to become greater than O(log n)
over a sequence of insertions
and deletions.
Instead, splay trees provide a slightly weaker (though still
meaningful) guarantee known as
an amortized bound, which is essentially just a bound on the
average time of a single opera-
tion over the course of several operations. In the context of
splay trees, one can show that
over the course of, say, n insertions to build a tree with n
elements, the average time of each
of these operations is O(log n) (but again, keeping in mind it is
possible for any single one
of these operations to take much longer than this).
Showing this guarantee is beyond the scope of this course
(although the details of the analy-
sis can be found in your textbook). Instead, in this assignment,
we will just be in interested
1
r splay:
N
root
root
2
1
1
2
l splay:
N
1
2
rr splay:
N
N
N
ll splay:
rl splay:
1
2
N
lr splay:
Figure 1: Illustration of the six possible cases for on a given
step of a splay operation.
in writing an implementation of a splay tree in Java that is
structured using inheritance.
Splay Tree Insertions and Deletions
To insert or delete an element from the tree, splay trees use the
same approach as the other
height-balancing trees we’ve discussed in class — first we
insert/deletion an element using
standard BST procedures, and then perform a “height-fixing”
procedure that rebalances the
tree. Thus, what distinguishes each of these height-balancing
trees from one another is how
they define their height-fixing procedures.
To fix the tree after both insertions and deletions, splay trees
use (as the name suggests)
a key subroutine known as a splay. A splay procedure begins at
some node N, and then
performs a series of rotations until N is the new root of the tree.
In particular, the splay
subroutine repeatedly applies one of the following six
operations on N while it is not yet the
root of the tree (each case is also illustrated in Figure 1):
• Case 1 (r splay): If N is currently the left child the root, then
perform a right
rotation on the root of the tree.
• Case 2 (l splay): If N is currently the right child the root, then
perform a left rotation
on the root of the tree.
2
• Case 3 (rr splay): If N is currently the left child of its parent,
and N’s parent is the
left child of N’s grandparent, then first perform a right rotation
on N’s grandparent,
and then perform and right rotation on N’s parent.
• Case 4 (ll splay): If N is currently the right child of its parent,
and N’s parent is the
right child of N’s grandparent, then first perform a left rotation
on N’s grandparent,
and then perform and left rotation on N’s parent.
• Case 5 (rl splay): If N is currently the left child of its parent,
and N’s parent is the
right child of N’s grandparent, then first perform a right
rotation on N’s parent, and
then perform and left rotation on N’s grandparent.
• Case 6 (lr splay): If N is currently the right child of its parent,
and N’s parent is
the left child of N’s grandparent, then first perform a left
rotation on N’s parent, and
then perform and right rotation on N’s grandparent.
A couple things to note: a) since either an r or l splay will be
performed if N is a child of
the root, it’s safe for us to assume that N has a grandparent in
the other cases, and b) note
that the order in which the parent and grandparent are rotated is
switched between rr/ll
splays versus rl/lr splays, i.e., rr/ll splays rotate the grandparent
first, whereas rl/lr splays
rotate the parent first.
Now that we’ve defined this splay operation, defining the fixing
procedure for both insertions
and deletions is straightforward. For insertions, we simply run
the splay procedure on the
newly inserted node. For deletions, we splay the parent of the
node that was deleted from
the tree (noting in the case where the node we removed was the
node originally the node
containing the successor of the element that was deleted, the
node we splay is the parent of
the successor).
API Details
The Java project you will amend contains five files, which form
a small inheritance hierarchy
(illustrated in Figure 2). In particular, the files included in the
project are as follows:
• Collection.java: An interface that defines a (very general)
template for a data struc-
ture containing a collection of elements (i.e., it must support
insertions, deletions, and
searches). There are no changes you need to make to this file.
• HeightBalancingTree.java: An abstract class that implements
the Collection in-
terface by giving a template for how a height-balancing tree
class should be imple-
mented (as well as explicitly defining methods that are common
subroutines for all
height-balancing trees, e.g., finding a node or performing a
rotation).
• RedBlackTree.java: A class that implements a red-black tree
data structure by ex-
tending from the abstract class HeightBalancingTree. There are
no changes you need
to make to this file.
3
Collection
(interface)
HeightBalancedTree
(abstract class)
RedBlackTree SplayTree
Figure 2: Inheritance hierarchy implemented in the assignment.
• SplayTree.java: A class that implements a splay tree data
structure by extending
from the abstract class HeightBalancingTree.
• TestHeightBalTree.java: A test file that will tests the
correctness of the overall
implementation of the RedBlackTree class (which is designed to
test your implemen-
tations of the rotation methods you write in
HeightBalancingTree), as well the cor-
rectness of your splay tree implementation. There are no
changes you need to make to
this file.
As in the previous assignment, many methods are already
written for you, so please famil-
iarize yourself with all the code in the project. In terms of the
methods you must write for
the assignment, in HeightBalancingTree.java you will
implement:
• protected void leftRotate(Node rotRoot): Performs a left
rotation on the subtree
rooted at rotRoot.
• protected void rightRotate(Node rotRoot): Performs a right
rotation on the sub-
tree rooted at rotRoot.
In SplayTree.java, you will implement:
• public void insert(T element): Insert element into the the splay
tree (implements
the corresponding method declaration in Colletion.java).
• public boolean delete(T element): Remove an occurrence of
element in the tree.
Returns true if element was removed; returns false otherwise
(also implements the
corresponding method declaration in Colletion.java).
4
• protected void insertionFix(Node<T> n): Rebalance the tree
after inserting node
n into the tree.
• protected void deletionFix(Node<T> del, Node<T> replace,
Node<T> parent):
Rebalances the tree after deleting node del from tree, which was
then replaced by node
replace (one its children nodes); node parent points to the
parent of the deleted node.
Note that in the case that the node that was actually deleted
from the tree was the
successor of the element to be deleted (i.e., when the element to
be deleted is stored at
a node with two children), del will be the node containing the
successor (and therefore
replace will be the child node that replaced the successor, and
parent is the parent
of the successor.)
• private void splay(Node<T> n): Perform a splay procedure
starting at node n (see
the previous section for the details of the algorithm).
Comments and Tips
• The TestHeightBalTree.java file tests the correctness your
trees by making sure
both the in-order and pre-order traversals of your tree matches
those produced by the
solution code. Keep in mind that as long as your implementation
satisfies the BST
property, your in-order traversals should match that of the
target solution (in partic-
ular, the in-order traversal should be all the elements in tree
given in sorted order).
A matching pre-order traversal means you’ve properly
implemented the methods that
modify the structure of the tree (rotations, splay, etc.).
• Observe that HeightBalancedTree is written so that all missing
child links, as well
the parent of the root, should point to nullNode. By default,
nullNode is set to be
null, but a deriving class can change this (as is the case for
RedBlackTree when it
defines its special “sentinel” null node that is black). Thus, all
checks for null links
should be for nullNode (and not for just null).
• When implementing both leftRotate() and rightRotate(), be
sure to properly up-
date all child and parent pointers. Note that you should not try
to change any pointers
of nullNode (as it may be null), and also be sure to update the
root when necessary.
• Your implementations of insert() and delete() in SplayTree
should be similar the
overriden implementations of the same methods in
RedBlackTree(), so be sure to use
the latter as guiding examples. On a related note, the most
involved methods you’ll
write should be leftRotate(), rightRotate(), and splay(). If your
code for the
other methods begins to look intricate, you should rethink your
approach.
• Just something to observe: Although you aren’t required to
understand the exact
structure of the TestHeightBalTree.java, this is a good file to
look at to see some
of the benefits of structuring these classes to use inheritance.
For example, using
inheritance allows us to write one method that is capable of
testing both types of
trees.
5
Code Retrieval and Submission
As with Coding Assignment 3, the entire netbeans project is
given as a .zip file on Canvas.
To complete your assignment, please modify the given files
(i.e., fill-in implementations for
each method that currently says “write this method”). To
submit, please submit the modi-
fied project as a .zip file on Canvas.
Evaluation
Your submission will again be scored a 50 point scale. The
point breakdown by category is
as follows.
• Overall Approach and Code Readability [10 points]: This
category will be
scored based on the overall structure and approach of your
implementation. For exam-
ple, how readable is your code? Did you include useful
comments? Can I understand
(with not too much effort) the approach you took for each
method?
• Method Implementation [20 points]: For this category, I will
pick two of methods
that you were asked to write for the assignment (for this
particular assignment, I will
grade one of the two rotation methods, as well as the splay()
method) and do a more
detailed evaluation of their implementations based on
correctness, efficiency, and code
readability.
• Empirical Testing [20 point; 10 points public; 10 points
private]: For this
category, you will receive a grade based on tests I’ll run on
your code. Half of the
points will come from public tests, which are included
TestHeightBalTree.java. The
other ten points will come from private tests.
6
2
Week 3 Assignment
Designing Lesson Plans: Evidence-Based Strategies
ESE 645 Lesson Design for Students
With Mild to Moderate Disabilities
Mary Ware
Instructor Shaneka Bell, EdD
July 20, 2018
Lesson Plan
Content Area or Developmental Focus: ELA
Age/Grade of Children: 2
Length of Lesson: 1 hour
Goal
Students should be able to understand reading, written, listening
comprehension as well as gain courage in peer interactions
Objective
· Reading comprehension and describing the main events
· Listening to comprehension and be able to point out the main
characters
· To read a comprehension fluently and be able to understand a
comprehension via listening
· Be prepared to interact with the peers in solving problems
together and improving the social skills.
Standards Included
CCSS.ELA-LITERACY.SL.2.1
Share with peer students the common topics that interested the
student in their class
CCSS.ELA-LITERACY.SL.2.2
Describe the primary ideas from the text that has been read
aloud.
CCSS.ELA-LITERACY.SL.2.3
Ask questions about the main events of the speaker to clarify
comprehension, gathering of additional information as well as
increase understanding of the main topic.
CCSS.ELA-LITERACY.SL.2.4
Describe the story recounting the appropriate and relevant facts
from the storybook, preferably by speaking loud in front of a
fellow group members
Materials
Read; Once Upon A Time Book by Niki Daly
Introduction
The interest of the student will be sparked by producing their
most exciting story books they have ever read. Each student
should produce their favorite books and give a small recall of
the storybook or describe the main characters in the book. The
students will then be asked about the challenges or the
difficulties they have encountered while reading the story
books. This will provide the room for the teacher to mention the
main ideas in the storybook which entails student who have
difficulties in reading comprehension, peer interactions, reading
slowly among others.
Lesson Development:
Direct Instruction
Guided Practice:
· Reading in small groups
· Reading aloud in the class
· Use peer tutoring for the students with special needs.
Individualized instructions on the students who are slow in
reading or learning will be applied.
· The students can use the smart board and draw images or
pictures that are connected to the main events from the
storybook.
· The student will share their understanding in groups of 2-3
fellow peers.
Informal assessment
· Student fluency in reading the comprehension aloud
· Student ability to share the story events to the class
· Student ability to speak aloud while reading the written
comprehension
Differentiation
· Have extended time for taking the tests, completing
assignments and responding to directions.
· Have daily visual or written schedules.
· The instructor should implement varying approaches in
teaching the students, that is the use of visual components and
modeling of tasks.
· Parents and the Special education teacher should communicate
daily on the progress of the student.
· The student should sit in front of the classroom.
· Reading comprehension sections aloud during exams or
assessments.
· Allow time for interaction among the students.
· Emphasize on peer tutoring.
· Have specially designed instructions
Assessment
(Practice/ Checking for
Understanding)
Independent practice:
Collaborative groups:
· Give details of the story from the beginning to the end with
different partners.
· Read the comprehension aloud while the other students are
listening.
Written Response
· The student will write the story from a written comprehension
· The student will write the story events from the listening
comprehension
· The student should recount and write the main events from the
group interaction in reading the comprehension
· The student should visualize the exciting part of the story and
draw pictures of the main characters
Closing
Closing the study lesson
· The students will share stories of the main character to the
fellow peers
· The student will exchange their picture with their fellow peers
References
English Language Arts Standards. (2018). Retrieved from
http://www.corestandards.org/ELA-Literacy/
Killian, S. (2018). Top 10 Evidence Based Teaching Strategies.
Retrieved from
http://www.evidencebasedteaching.org.au/evidence-based-
teaching-strategies/
Rubie‐Davies, C. M. (2007). Classroom interactions: Exploring
the practices of high‐and low‐expectation teachers. British
Journal of Educational Psychology, 77(2), 289-306.
Supports, Modifications, and Accommodations for Students.
(2017). Retrieved from
http://www.parentcenterhub.org/repository/accommodations/#te
stinG
Collection/build.xml
Builds, tests, and runs the project Collection.
Collection/build/classes/collection/Collection.classpackage
collection;
publicabstractinterface Collection {
publicabstract void insert(Object);
publicabstract boolean delete(Object);
publicabstract boolean contains(Object);
publicabstract int getSize();
}
Collection/build/classes/collection/HeightBalancedTree$Node.c
lasspackage collection;
publicsynchronizedclass HeightBalancedTree$Node {
protected HeightBalancedTree$Node left;
protected HeightBalancedTree$Node right;
protected HeightBalancedTree$Node parent;
protected Object data;
protected void
HeightBalancedTree$Node(HeightBalancedTree,
HeightBalancedTree$Node, HeightBalancedTree$Node,
HeightBalancedTree$Node, Object);
}
Collection/build/classes/collection/HeightBalancedTree.classpa
ckage collection;
publicabstractsynchronizedclass HeightBalancedTree
implements Collection {
HeightBalancedTree$Node root;
int size;
HeightBalancedTree$Node nullNode;
protectedstaticfinal int DELETED = 0;
protectedstaticfinal int REPLACED = 1;
protectedstaticfinal int PARENT = 2;
public void HeightBalancedTree();
protectedabstract void
insertionFix(HeightBalancedTree$Node);
protectedabstract void
deletionFix(HeightBalancedTree$Node,
HeightBalancedTree$Node, HeightBalancedTree$Node);
public int getSize();
public boolean contains(Comparable);
protected HeightBalancedTree$Node
insertNode(Comparable);
public java.util.ArrayList deleteNode(Comparable);
protected HeightBalancedTree$Node findNode(Comparable);
protected void leftRotate(HeightBalancedTree$Node);
protected void rightRotate(HeightBalancedTree$Node);
protected HeightBalancedTree$Node
findMinNode(HeightBalancedTree$Node);
protected void setParentLink(HeightBalancedTree$Node,
HeightBalancedTree$Node, HeightBalancedTree$Node);
public String toString();
public String inOrderString();
protected void preOrder(HeightBalancedTree$Node,
java.util.ArrayList);
protected void inOrder(HeightBalancedTree$Node,
java.util.ArrayList);
}
Collection/build/classes/collection/RedBlackTree$RBNode.clas
spackage collection;
publicsynchronizedclass RedBlackTree$RBNode extends
HeightBalancedTree$Node {
protected boolean color;
protected void RedBlackTree$RBNode(RedBlackTree,
HeightBalancedTree$Node, HeightBalancedTree$Node,
HeightBalancedTree$Node, Object, boolean);
}
Collection/build/classes/collection/RedBlackTree.classpackage
collection;
publicsynchronizedclass RedBlackTree extends
HeightBalancedTree {
privatestaticfinal boolean RED = 1;
privatestaticfinal boolean BLACK = 0;
public void RedBlackTree();
public void insert(Comparable);
public boolean delete(Comparable);
protected void insertionFix(HeightBalancedTree$Node);
protected void deletionFix(HeightBalancedTree$Node,
HeightBalancedTree$Node, HeightBalancedTree$Node);
private RedBlackTree$RBNode
convertToRBNode(HeightBalancedTree$Node, boolean);
}
Collection/build/classes/collection/SplayTree.classpackage
collection;
publicsynchronizedclass SplayTree extends HeightBalancedTree
{
public void SplayTree();
public void insert(Comparable);
public boolean delete(Comparable);
protected void insertionFix(HeightBalancedTree$Node);
protected void deletionFix(HeightBalancedTree$Node,
HeightBalancedTree$Node, HeightBalancedTree$Node);
private void splay(HeightBalancedTree$Node);
}
Collection/build/classes/collection/TestHeightBalTrees.classpac
kage collection;
publicsynchronizedclass TestHeightBalTrees {
privatestaticfinal String[] INORDER;
privatestaticfinal String[] ROT_PREORDER;
privatestaticfinal String[] SPLAY_PREORDER;
public void TestHeightBalTrees();
publicstatic int doTests(HeightBalancedTree, String[],
String[]);
publicstatic void testOne(HeightBalancedTree);
publicstatic void testTwo(HeightBalancedTree);
publicstatic void testThree(HeightBalancedTree);
publicstatic void testFour(HeightBalancedTree);
publicstatic void testFive(HeightBalancedTree);
publicstatic void printTestMessage(HeightBalancedTree, int,
int[], String[], String[]);
publicstatic void main(String[]);
static void <clinit>();
}
Collection/manifest.mf
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
Collection/nbproject/build-impl.xml
Must set src.dir
Must set test.src.dir
Must set build.dir
Must set dist.dir
Must set build.classes.dir
Must set dist.javadoc.dir
Must set build.test.classes.dir
Must set build.test.results.dir
Must set build.classes.excludes
Must set dist.jar
Must set javac.includes
No tests executed.
Must set JVM to use for profiling in profiler.info.jvm
Must set profiler agent JVM arguments in
profiler.info.jvmargs.agent
Must select some files in the IDE or set javac.includes
To run this application from the command line without
Ant, try:
java -jar "${dist.jar.resolved}"
Must select one file in the IDE or set run.class
Must select one file in the IDE or set run.class
Must select one file in the IDE or set debug.class
Must select one file in the IDE or set debug.class
Must set fix.includes
This target only works when run from inside the NetBeans
IDE.
Must select one file in the IDE or set profile.class
This target only works when run from inside the NetBeans
IDE.
This target only works when run from inside the NetBeans
IDE.
This target only works when run from inside the NetBeans
IDE.
Must select one file in the IDE or set run.class
Must select some files in the IDE or set test.includes
Must select one file in the IDE or set run.class
Must select one file in the IDE or set applet.url
Must select some files in the IDE or set javac.includes
Some tests failed; see details above.
Must select some files in the IDE or set test.includes
Some tests failed; see details above.
Must select some files in the IDE or set test.class
Must select some method in the IDE or set test.method
Some tests failed; see details above.
Must select one file in the IDE or set test.class
Must select one file in the IDE or set test.class
Must select some method in the IDE or set test.method
Must select one file in the IDE or set applet.url
Must select one file in the IDE or set applet.url
Collection/nbproject/genfiles.properties
build.xml.data.CRC32=a24dc44d
build.xml.script.CRC32=1fd00482
[email protected]
# This file is used by a NetBeans-based IDE to track changes in
generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will
never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=a24dc44d
nbproject/build-impl.xml.script.CRC32=f6a04097
nbproject/[email protected]
Collection/nbproject/private/private.properties
compile.on.save=true
user.properties.file=C:UsersnbkellAppDataRoamingNetB
eans8.2build.properties
Collection/nbproject/private/private.xml
file:/C:/Users/Nat/Box/CSC%20330%20Spring%202019/homew
orks/coding-3-base/Collection/src/collection/Collection.java
file:/C:/Users/Nat/Box/CSC%20330%20Spring%202019/homew
orks/coding-3-base/Collection/src/collection/SplayTree.java
file:/C:/Users/Nat/Box/CSC%20330%20Spring%202019/homew
orks/coding-3-
base/Collection/src/collection/TestHeightBalTrees.java
file:/C:/Users/Nat/Box/CSC%20330%20Spring%202019/homew
orks/coding-3-base/Collection/src/collection/RedBlackTree.java
file:/C:/Users/Nat/Box/CSC%20330%20Spring%202019/homew
orks/coding-3-
base/Collection/src/collection/HeightBalancedTree.java
Collection/nbproject/project.properties
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processor.options=
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.
dir}/ap-source-output
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection
transport:
#debug.transport=dt_socket
debug.classpath=
${run.classpath}
debug.test.classpath=
${run.test.classpath}
# Files in build.classes.dir which should be excluded from
distribution jar
dist.archive.excludes=
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/Collection.jar
dist.javadoc.dir=${dist.dir}/javadoc
excludes=
includes=**
jar.compress=false
javac.classpath=
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.external.vm=true
javac.processorpath=
${javac.classpath}
javac.source=1.8
javac.target=1.8
javac.test.classpath=
${javac.classpath}:
${build.classes.dir}
javac.test.processorpath=
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=collection.TestHeightBalTrees
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false
platform.active=default_platform
run.classpath=
${javac.classpath}:
${build.classes.dir}
# Space-separated list of JVM arguments used when running the
project.
# You may also define separate properties like run-sys-
prop.name=value instead of -Dname=value.
# To set system properties for unit tests define test-sys-
prop.name=value:
run.jvmargs=
run.test.classpath=
${javac.test.classpath}:
${build.test.classes.dir}
source.encoding=UTF-8
src.dir=src
test.src.dir=test
Collection/nbproject/project.xml
org.netbeans.modules.java.j2seproject
Collection
Collection/src/collection/Collection.javaCollection/src/collectio
n/Collection.javapackage collection;
/**
* Interface for a collection class.
* Coding Assignment 3, CSC 330, Spring 2019
* (Note there is nothing in this file for you to change).
* @author Nathaniel Kell
* @param <T> type of objects in the collection.
*/
publicinterfaceCollection<T>{
/**
* Insert an element into the collection.
* @param element: object to be inserted
*/
publicvoid insert(T element);
/**
* Delete an element from the collection.
* @param element: object to be deleted
* @return true if the element was deleted (false otherwise).
*/
publicboolean delete(T element);
/**
* Check if an element exists in the collection.
* @param element: object to be checked for containment.
* @return true if the element exists in the collection (false o
therwise).
*/
publicboolean contains(T element);
/**
* Returns the number of elements in the collection.
* @return size of the collection.
*/
publicint getSize();
}
Collection/src/collection/HeightBalancedTree.javaCollection/sr
c/collection/HeightBalancedTree.javapackage collection;
import java.util.*;
/**
* Abstract class for height balancing trees to extend from.
* Coding Assignment 3, CSC 330, Spring 2019
* @author *YOUR NAME HERE*
* @param <T> type of objects in the tree.
*/
publicabstractclassHeightBalancedTree<T extendsComparable<
T>>implementsCollection<T>{
Node root;
int size;
Node nullNode;// node to serve as null pointer
/* Indices for the nodes returned by deleteNode() */
protectedfinalstaticint DELETED =0;
protectedfinalstaticint REPLACED =1;
protectedfinalstaticint PARENT =2;
/* Node class used for storing the structure of the tree */
protectedclassNode<T>{
protectedNode left, right, parent;
protected T data;
protectedNode(Node l,Node r,Node p , T d){
left = l;
right = r;
parent = p;
data = d;
}
}
/* Construct an emepty height balancing tree */
publicHeightBalancedTree(){
size =0;
nullNode =null;
root = nullNode;
}
/**
* Balances the tree after an insertion (starting at node n).
* @param n : node where balancing procedure begins
*/
protectedabstractvoid insertionFix(Node<T> n);
/**
* Balances the tree after a deletion.
* @param del : node that was just deleted from the tree.
* @param replace: node that took the place del in the tree.
* @param parent: parent of del.
*/
protectedabstractvoid deletionFix(Node<T> del,Node<T> replac
e,Node<T> parent);
@Override
publicint getSize(){
return size;
}
@Override
publicboolean contains(T element){
return findNode(element)!= nullNode;
}
/**
* Insert a new node into the tree and return the newly constr
ucted node.
* @param element : element to be inserted into the tree.
* @return : newly inserted node.
*/
protectedNode<T> insertNode(T element){
Node<T> current = root;
Node<T> par = nullNode;
boolean left =false;// whether we take left or right links
/* Find the correct location to insert */
while(current != nullNode){
par = current;
if(current.data.compareTo(element)>=0){
current = current.left;
left =true;
}
else{
current = current.right;
left =false;
}
}
Node<T> newNode =newNode(nullNode, nullNode, par, elemen
t);
/* Check if new node is the root */
if(par == nullNode)
root = newNode;
/* Set up parent links */
elseif(left ==true)
par.left = newNode;
else
par.right = newNode;
return newNode;
}
/**
* Deletes a node from the tree with data equal to element.
* @param element : element to be deleted from the tree.
* @return an array list that contains the node deleted, the no
de
* that replaced it, and the parent of the deleted node.
*/
publicArrayList<Node<T>> deleteNode(T element){
Node<T> del = findNode(element);
Node<T> replace = nullNode;
Node<T> parent = nullNode;
ArrayList<Node<T>> ret =newArrayList();
ret.add(del);
ret.add(replace);
ret.add(parent);
/* The node does not exist in the tree */
if(del != nullNode){
/* Case 1: left is null */
if(del.left == nullNode){
replace = del.right;
setParentLink(del.parent, del, del.right);
}
/* Case 2: right is null */
elseif(del.right == nullNode){
replace = del.left;
setParentLink(del.parent, del, del.left);
}
/* Case 4: two children */
else{
Node<T> successor = findMinNode(del.right);
del.data = successor.data;
setParentLink(successor.parent, successor, successor.
right);
/* In this case, we've deleteed successor, and its right
child has taken its place */
del = successor;
replace = del.right;
}
ret.set(DELETED,del);
ret.set(REPLACED,replace);
ret.set(PARENT, del.parent);
}
return ret;
}
/**
* Searches for and returns a node with data equal to element.
* @param element: method finds a node with data equal to e
lement.
* @return node that has data equal to element.
*/
protectedNode<T> findNode(T element){
Node<T> current = root;
while(current != nullNode){
if(current.data.equals(element))
return current;
elseif(current.data.compareTo(element)>=0)
current = current.left;
else
current = current.right;
}
return nullNode;
}
/**
* Perform a left rotation on the subtree rooted at rotRoot.
* @param rotRoot: root of the subtree to be rotated.
*/
protectedvoid leftRotate(Node rotRoot){
/**
*
*
*** WRITE THIS METHOD ***
*
*
**/
}
/**
* Perform a right rotation on the subtree rooted at rotRoot.
* @param rotRoot: root of the subtree to be rotated.
*/
protectedvoid rightRotate(Node rotRoot){
/**
*
*
*** WRITE THIS METHOD ***
*
*
**/
}
/**
* Find the minimum node the subtree rooted at node n.
* @param n : starting node of the search
* @return node with minimum value in the subtree rooted at
n.
*/
protectedNode<T> findMinNode(Node<T> n){
Node<T> cur = n;
while(cur.left != nullNode)
cur = cur.left;
return cur;
}
/**
* Replaces parent's child pointer to child with newChild.
* @param par : node to replace child link.
* @param child : original child of parent.
* @param newChild : new child of parent.
*/
protectedvoid setParentLink(Node<T> par,Node<T> child,Node
<T> newChild){
if(newChild != nullNode)
newChild.parent = par;
if(par != nullNode){
if(child == par.left)
par.left = newChild;
else
par.right = newChild;
}
else
root = newChild;
}
/**
* Return the pre-order representation of the tree
* @return string containing the pre-
order sequence of the tree.
*/
@Override
publicString toString(){
ArrayList<String> stringList =newArrayList();
preOrder(root, stringList);
String treeString ="";
for(int i =0; i < stringList.size()-1; i++)
treeString += stringList.get(i)+", ";
treeString += stringList.get(stringList.size()-1);
return treeString;
}
/**
* Return the in-order representation of the tree
* @return string containing the in-
order sequence of the tree.
*/
publicString inOrderString(){
ArrayList<String> stringList =newArrayList();
inOrder(root, stringList);
String treeString ="";
for(int i =0; i < stringList.size()-1; i++)
treeString += stringList.get(i)+", ";
treeString += stringList.get(stringList.size()-1);
return treeString;
}
/**
* Recursively perform an in-order traversal or the tree.
* @param cur : current node of the traversal.
* @param stringList : string that will contain the sequence a
t the end of search.
*/
protectedvoid preOrder(Node<T> cur,ArrayList<String> stringL
ist){
if(cur != nullNode){
stringList.add(cur.data.toString());
preOrder(cur.left, stringList);
preOrder(cur.right, stringList);
}
}
/**
* Recursively perform an in-order traversal or the tree.
* @param cur : current node of the traversal.
* @param stringList : string that will contain the sequence a
t the end of search.
*/
protectedvoid inOrder(Node<T> cur,ArrayList<String> stringLi
st){
if(cur != nullNode){
inOrder(cur.left, stringList);
stringList.add(cur.data.toString());
inOrder(cur.right, stringList);
}
}
}
Collection/src/collection/RedBlackTree.javaCollection/src/colle
ction/RedBlackTree.javapackage collection;
import java.util.ArrayList;
/**
* Implementation of a red-black tree.
* Coding Assignment 3, CSC 330, Spring 2019
* (Note there is nothing in this file for you to change)
* @author Nathaniel Kell
* @param <T> type of objects in the tree.
*/
publicclassRedBlackTree<T extendsComparable<T>>extendsHe
ightBalancedTree<T>{
/* boolean values corresponding to red and black. */
privatestaticfinalboolean RED =true;
privatestaticfinalboolean BLACK =false;
/* Modified node class that now has a color value */
protectedclassRBNode<T>extendsNode<T>{
protectedboolean color;
protectedRBNode(Node l,Node r,Node p , T d,boolean c){
super(l, r, p, d);
color = c;
}
}
/* Construct an empty red-black tree */
publicRedBlackTree(){
super();
nullNode =newRBNode(null,null,null,null, BLACK);
nullNode.parent = nullNode;
nullNode.left = nullNode;
nullNode.right = nullNode;
root = nullNode;
}
@Override
publicvoid insert(T element){
Node<T> newNode = insertNode(element);
RBNode<T>RBnewNode= convertToRBNode(newNode, RED);
if(((RBNode)RBnewNode.parent).color == RED)
insertionFix(RBnewNode);
((RBNode)root).color = BLACK;
size++;
}
@Override
publicboolean delete(T element){
ArrayList<Node<T>> delNodes = deleteNode(element);
Node<T> del = delNodes.get(DELETED);
Node<T> replace = delNodes.get(REPLACED);
Node<T> parent = delNodes.get(PARENT);
if(del == nullNode)
returnfalse;
if(((RBNode)del).color == BLACK)
deletionFix(del, replace, parent);
size--;
returntrue;
}
@Override
protectedvoid insertionFix(Node<T> n){
RBNode cur =(RBNode)n;
while(((RBNode)cur.parent).color == RED){
RBNode grandparent =(RBNode)cur.parent.parent;
/* Meta case 1: cur's parent is a left child of its parent */
if(cur.parent == grandparent.left){
RBNode aunt =(RBNode)grandparent.right;
/* Case 1: cur's aunt is red */
if(aunt.color == RED){
((RBNode)cur.parent).color = BLACK;
aunt.color = BLACK;
grandparent.color = RED;
cur = grandparent;
}
else{
/* Case 2: aunt is black and cur is a right child */
if(cur == cur.parent.right){
leftRotate((cur.parent));
cur =(RBNode)cur.left;
}
/* Case 3: aunt is black and cur is a left child */
((RBNode)cur.parent).color = BLACK;
grandparent.color = RED;
rightRotate(grandparent);
}
}
/* Meta case 2: cur's parent is a right child of its parent
* (each subcase are symmetric to those of meta-
case 1) */
else{
RBNode aunt =(RBNode)grandparent.left;
if(aunt.color == RED){
((RBNode)cur.parent).color = BLACK;
aunt.color = BLACK;
grandparent.color = RED;
cur = grandparent;
}
else{
if(cur == cur.parent.left){
rightRotate((cur.parent));
cur =(RBNode)cur.right;
}
((RBNode)cur.parent).color = BLACK;
grandparent.color = RED;
leftRotate(grandparent);
}
}
}// end while
}
@Override
protectedvoid deletionFix(Node<T> del,Node<T> replace,Node
<T> parent){
RBNode<T> cur =(RBNode)replace;
while(cur != root && cur.color == BLACK){
RBNode<T> par =(RBNode)cur.parent;
if(cur == nullNode)
par =(RBNode)parent;
/* Meta-case 1: cure is a left child */
if(cur == par.left){
RBNode<T> sibling =(RBNode)par.right;
/* Case 1: cur's sibling is red */
if(sibling.color == RED){
sibling.color = BLACK;
par.color = RED;
leftRotate(par);
sibling =(RBNode)par.right;
}
/* Case 2: cur's sibling is black and sibling's children are both b
lack */
if(((RBNode)sibling.left).color == BLACK &&((RBNode)siblin
g.right).color == BLACK){
sibling.color = RED;
cur = par;
}
/* Case 3: cur's sibling is black and just sibling's right child is b
lack */
else{
if(((RBNode)sibling.right).color == BLACK){
((RBNode)sibling.left).color = BLACK;
sibling.color = RED;
rightRotate(sibling);
sibling =(RBNode)par.right;
}
/* Case 4: cur's sibling is black and sibling's left child is red */
sibling.color = par.color;
par.color = BLACK;
((RBNode)sibling.right).color = BLACK;
leftRotate(par);
cur =(RBNode)root;
}
}
/* Meta-case 2: cur is a right child
* (subcases are symmetric to those of meta-case 1) */
else{
RBNode<T> sibling =(RBNode)par.left;
if(sibling.color == RED){
sibling.color = BLACK;
par.color = RED;
rightRotate(par);
sibling =(RBNode)par.left;
}
if(((RBNode)sibling.left).color == BLACK &&((RBNode)siblin
g.right).color == BLACK){
sibling.color = RED;
cur = par;
}
else{
if(((RBNode)sibling.left).color == BLACK){
((RBNode)sibling.right).color = BLACK;
sibling.color = RED;
leftRotate(sibling);
sibling =(RBNode)par.left;
}
sibling.color = par.color;
par.color = BLACK;
((RBNode)sibling.left).color = BLACK;
rightRotate(par);
cur =(RBNode)root;
}
}
}// end while
cur.color = BLACK;
}
/**
* Convert a standard node into a red-
black node (where the the RBnode
* replaces the standard node in the tree with respect to its lin
ks).
* @param n : standard node to be converted.
* @param c : color of the red-black node
* @return converted RBNode.
*/
privateRBNode<T> convertToRBNode(Node<T> n,boolean c){
RBNode<T> rbN =newRBNode(n.left, n.right, n.parent, n.data,
c);
if(rbN.parent == nullNode)
root = rbN;
elseif(rbN.parent.left == n)
rbN.parent.left =(Node)rbN;
else
rbN.parent.right =(Node)rbN;
return rbN;
}
}
Collection/src/collection/SplayTree.javaCollection/src/collectio
n/SplayTree.javapackage collection;
importstatic collection.HeightBalancedTree.DELETED;
import java.util.ArrayList;
/**
* SplayTree height balancing tree class.
* Coding Assignment 3, CSC 330, Spring 2019
* @author *YOUR NAME HERE*
* @param <T> type of objects in the tree.
*/
publicclassSplayTree<T extendsComparable<T>>extendsHeight
BalancedTree<T>{
/* Construct an empty splay tree*/
publicSplayTree(){
super();
}
@Override
publicvoid insert(T element){
/**
*
*
*** WRITE THIS METHOD ***
*
*
**/
}
@Override
publicboolean delete(T element){
/**
*
*
*** WRITE THIS METHOD ***
*
*
**/
}
@Override
protectedvoid insertionFix(Node<T> n){
/**
*
*
*** WRITE THIS METHOD ***
*
*
**/
}
@Override
protectedvoid deletionFix(Node<T> del,Node<T> replace,Node
<T> parent){
/**
*
*
*** WRITE THIS METHOD ***
*
*
**/
}
/**
* Splay a node to the root of the tree.
* @param n : node to be splayed to the top of the tree
*/
privatevoid splay(Node<T> n){
/**
*
*
*** WRITE THIS METHOD ***
*
*
**/
}
}
Collection/src/collection/TestHeightBalTrees.javaCollection/src
/collection/TestHeightBalTrees.javapackage collection;
/**
* Coding Assignment 3, CSC 330, Spring 2019
* (Note there is nothing in this file for you to change).
* @author Nathaniel Kell
*/
publicclassTestHeightBalTrees{
privatestaticfinalString[] INORDER =
{
"80, 90, 100",
"20, 30, 35, 40, 45, 50, 60, 70, 75, 80, 90, 100",
"20, 30, 35, 40, 45, 50, 60, 70, 75, 80, 85, 90, 100, 110, 120, 13
0, 140, 150",
"1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 30, 35, 40, 45, 50, 60, 70, 75, 80, 85
, 90, 100, 110, 120, 130, 140, 150, 200, 210, 220, 230, 240, 250
",
"2, 5, 6, 8, 9, 20, 30, 35, 70, 85, 100, 120, 130, 150, 220, 230, 2
40",
};
privatestaticfinalString[] ROT_PREORDER =
{
"90, 80, 100",
"75, 45, 35, 30, 20, 40, 60, 50, 70, 90, 80, 100",
"75, 45, 35, 30, 20, 40, 60, 50, 70, 110, 90, 80, 85, 100, 130, 12
0, 140, 150",
"110, 45, 20, 6, 4, 2, 1, 3, 5, 8, 7, 9, 35, 30, 40, 75, 60, 50, 70, 9
0, 80, 85, 100, 150, 130, 120, 140, 210, 200, 230, 220, 240, 250
",
"70, 6, 2, 5, 20, 8, 9, 35, 30, 120, 85, 100, 220, 150, 130, 240, 2
30"
};
privatestaticfinalString[] SPLAY_PREORDER =
{
"80, 90, 100",
"20, 30, 35, 40, 45, 50, 60, 70, 75, 80, 90, 100",
"85, 30, 20, 50, 40, 35, 45, 80, 70, 60, 75, 140, 120, 110, 90, 10
0, 130, 150",
"1, 2, 3, 4, 5, 6, 7, 8, 9, 250, 230, 210, 85, 20, 30, 50, 40, 35, 45
, 80, 70, 60, 75, 200, 150, 140, 120, 110, 90, 100, 130, 220, 240
",
"120, 9, 5, 2, 8, 6, 70, 30, 20, 35, 85, 100, 150, 130, 230, 220, 2
40",
};
publicstaticint doTests(HeightBalancedTree<Integer> tree,Strin
g[] inorderStrings,String[] preOrderStrings){
int[] totalCorrect ={0};
int testNumber =1;
/* Test 1 */
testOne(tree);
printTestMessage(tree, testNumber, totalCorrect, inorderSt
rings, preOrderStrings);
testNumber++;
/* Test 2 */
testTwo(tree);
printTestMessage(tree, testNumber, totalCorrect, inorderSt
rings, preOrderStrings);
testNumber++;
/* Test 3 */
testThree(tree);
printTestMessage(tree, testNumber, totalCorrect, inorderSt
rings, preOrderStrings);
testNumber++;
/* Test 4 */
testFour(tree);
printTestMessage(tree, testNumber, totalCorrect, inorderSt
rings, preOrderStrings);
testNumber++;
/* Test 5 */
testFive(tree);
printTestMessage(tree, testNumber, totalCorrect, inorderSt
rings, preOrderStrings);
return totalCorrect[0];
}
/* Modify the tree for test 1 */
publicstaticvoid testOne(HeightBalancedTree<Integer> tree){
tree.insert(100);
tree.insert(90);
tree.insert(80);
}
/* Modify the tree for test 2 */
publicstaticvoid testTwo(HeightBalancedTree<Integer> tree){
tree.insert(70);
tree.insert(75);
tree.insert(60);
tree.insert(50);
tree.insert(45);
tree.insert(40);
tree.insert(30);
tree.insert(35);
tree.insert(20);
}
/* Modify the tree for test 3 */
publicstaticvoid testThree(HeightBalancedTree<Integer> tree){
tree.insert(110);
tree.insert(120);
tree.insert(130);
tree.insert(140);
tree.insert(150);
tree.insert(85);
}
/* Modify the tree for test 4 */
publicstaticvoid testFour(HeightBalancedTree<Integer> tree){
tree.insert(200);
tree.insert(210);
tree.insert(220);
tree.insert(230);
tree.insert(240);
tree.insert(250);
tree.insert(9);
tree.insert(8);
tree.insert(7);
tree.insert(6);
tree.insert(5);
tree.insert(4);
tree.insert(3);
tree.insert(2);
tree.insert(1);
}
/* Modify the tree for test 5 */
publicstaticvoid testFive(HeightBalancedTree<Integer> tree){
tree.delete(80);
tree.delete(110);
tree.delete(60);
tree.delete(40);
tree.delete(90);
tree.delete(140);
tree.delete(75);
tree.delete(45);
tree.delete(200);
tree.delete(210);
tree.delete(250);
tree.delete(7);
tree.delete(4);
tree.delete(3);
tree.delete(1);
tree.delete(50);
}
/* Print test results of a test */
publicstaticvoid printTestMessage(HeightBalancedTree<Integer
> tree,
int tNum,int[] totalCorrect,String[] inOrderTests,String[] preOr
derTests){
System.out.printf("Test Number: %dn", tNum);
System.out.printf("Target in-order sequence: %sn"
+"Produced in-order sequence: %sn"
+"Target pre-order sequence: %sn"
+"Produced pre-order sequence: %sn",
inOrderTests[tNum-
1], tree.inOrderString(), preOrderTests[tNum-
1], tree.toString());
if(inOrderTests[tNum-
1].equals(tree.inOrderString())&& preOrderTests[tNum-
1].equals(tree.toString())){
System.out.println("*** CORRECT ***n");
totalCorrect[0]++;
}
else
System.out.println("*** INCORRECT ***n");
}
/**
* @param args the command line arguments
*/
publicstaticvoid main(String[] args){
/* Rotation tests.*/
System.out.println("n**** ROTATION TESTS *****");
RedBlackTree<Integer> tree =newRedBlackTree();
int totalRotCorrect = doTests(tree, INORDER, ROT_PREORDE
R);
System.out.printf("Total Rotation Tests Correct: %dn", totalRo
tCorrect);
/* SplayTreee tests */
System.out.println("n-nn**** SPLAY TREE TESTS *****");
SplayTree<Integer> sTree =newSplayTree();
int totalSplayCorrect = doTests(sTree, INORDER, SPLAY_PR
EORDER);
System.out.printf("Total Splay Tree TayTrests Correct: %dn", t
otalSplayCorrect);
/* Total correct.*/
System.out.printf("nTotal Overall Correct: %dn", totalRotCorr
ect + totalSplayCorrect);
}
}

Coding Assignment 3CSC 330 Advanced Data Structures, Spri.docx

  • 1.
    Coding Assignment 3 CSC330: Advanced Data Structures, Spring 2019 Released Monday, April 15, 2019 Due on Canvas on Wednesday, May 1, at 11:59pm Overview In this assignment, you’ll implement another variant of a height-balancing tree known as a splay tree. The assignment will also give you an opportunity to work with Java inheritance; in particular, the base code that you’ll amend is structured so that your SplayTree class extends from an abstract class called HeightBalancingTree, which gives a general template for how a height-balancing tree should be defined. As always, please carefully read the entire write-up before you begin coding your submission. Splay Trees As mentioned above, a splay tree is another example of a height-balancing tree — a binary search tree that, upon either an insertion or deletion, modifies the tree through a sequence of rotations in order to reduce the overall height of the tree. However, splay trees differ from the other height-balancing trees we’ve seen (AVL trees,
  • 2.
    red-black trees) interms of the type of guarantees that they provide. In particular, recall that both AVL trees and red-black trees maintain the property that after any insertion or deletion, the height of the tree is O(log n), where n is the number of elements in the tree. Splay trees unfortunately do not provide this (fairly strong) guarantee; namely, it is possible for the height of a splay tree to become greater than O(log n) over a sequence of insertions and deletions. Instead, splay trees provide a slightly weaker (though still meaningful) guarantee known as an amortized bound, which is essentially just a bound on the average time of a single opera- tion over the course of several operations. In the context of splay trees, one can show that over the course of, say, n insertions to build a tree with n elements, the average time of each of these operations is O(log n) (but again, keeping in mind it is possible for any single one of these operations to take much longer than this). Showing this guarantee is beyond the scope of this course (although the details of the analy- sis can be found in your textbook). Instead, in this assignment, we will just be in interested 1 r splay: N
  • 3.
  • 4.
    lr splay: Figure 1:Illustration of the six possible cases for on a given step of a splay operation. in writing an implementation of a splay tree in Java that is structured using inheritance. Splay Tree Insertions and Deletions To insert or delete an element from the tree, splay trees use the same approach as the other height-balancing trees we’ve discussed in class — first we insert/deletion an element using standard BST procedures, and then perform a “height-fixing” procedure that rebalances the tree. Thus, what distinguishes each of these height-balancing trees from one another is how they define their height-fixing procedures. To fix the tree after both insertions and deletions, splay trees use (as the name suggests) a key subroutine known as a splay. A splay procedure begins at some node N, and then performs a series of rotations until N is the new root of the tree. In particular, the splay subroutine repeatedly applies one of the following six operations on N while it is not yet the root of the tree (each case is also illustrated in Figure 1): • Case 1 (r splay): If N is currently the left child the root, then perform a right rotation on the root of the tree. • Case 2 (l splay): If N is currently the right child the root, then
  • 5.
    perform a leftrotation on the root of the tree. 2 • Case 3 (rr splay): If N is currently the left child of its parent, and N’s parent is the left child of N’s grandparent, then first perform a right rotation on N’s grandparent, and then perform and right rotation on N’s parent. • Case 4 (ll splay): If N is currently the right child of its parent, and N’s parent is the right child of N’s grandparent, then first perform a left rotation on N’s grandparent, and then perform and left rotation on N’s parent. • Case 5 (rl splay): If N is currently the left child of its parent, and N’s parent is the right child of N’s grandparent, then first perform a right rotation on N’s parent, and then perform and left rotation on N’s grandparent. • Case 6 (lr splay): If N is currently the right child of its parent, and N’s parent is the left child of N’s grandparent, then first perform a left rotation on N’s parent, and then perform and right rotation on N’s grandparent. A couple things to note: a) since either an r or l splay will be performed if N is a child of the root, it’s safe for us to assume that N has a grandparent in the other cases, and b) note that the order in which the parent and grandparent are rotated is
  • 6.
    switched between rr/ll splaysversus rl/lr splays, i.e., rr/ll splays rotate the grandparent first, whereas rl/lr splays rotate the parent first. Now that we’ve defined this splay operation, defining the fixing procedure for both insertions and deletions is straightforward. For insertions, we simply run the splay procedure on the newly inserted node. For deletions, we splay the parent of the node that was deleted from the tree (noting in the case where the node we removed was the node originally the node containing the successor of the element that was deleted, the node we splay is the parent of the successor). API Details The Java project you will amend contains five files, which form a small inheritance hierarchy (illustrated in Figure 2). In particular, the files included in the project are as follows: • Collection.java: An interface that defines a (very general) template for a data struc- ture containing a collection of elements (i.e., it must support insertions, deletions, and searches). There are no changes you need to make to this file. • HeightBalancingTree.java: An abstract class that implements the Collection in- terface by giving a template for how a height-balancing tree class should be imple- mented (as well as explicitly defining methods that are common subroutines for all
  • 7.
    height-balancing trees, e.g.,finding a node or performing a rotation). • RedBlackTree.java: A class that implements a red-black tree data structure by ex- tending from the abstract class HeightBalancingTree. There are no changes you need to make to this file. 3 Collection (interface) HeightBalancedTree (abstract class) RedBlackTree SplayTree Figure 2: Inheritance hierarchy implemented in the assignment. • SplayTree.java: A class that implements a splay tree data structure by extending from the abstract class HeightBalancingTree. • TestHeightBalTree.java: A test file that will tests the correctness of the overall implementation of the RedBlackTree class (which is designed to test your implemen- tations of the rotation methods you write in HeightBalancingTree), as well the cor- rectness of your splay tree implementation. There are no changes you need to make to this file.
  • 8.
    As in theprevious assignment, many methods are already written for you, so please famil- iarize yourself with all the code in the project. In terms of the methods you must write for the assignment, in HeightBalancingTree.java you will implement: • protected void leftRotate(Node rotRoot): Performs a left rotation on the subtree rooted at rotRoot. • protected void rightRotate(Node rotRoot): Performs a right rotation on the sub- tree rooted at rotRoot. In SplayTree.java, you will implement: • public void insert(T element): Insert element into the the splay tree (implements the corresponding method declaration in Colletion.java). • public boolean delete(T element): Remove an occurrence of element in the tree. Returns true if element was removed; returns false otherwise (also implements the corresponding method declaration in Colletion.java). 4 • protected void insertionFix(Node<T> n): Rebalance the tree after inserting node n into the tree.
  • 9.
    • protected voiddeletionFix(Node<T> del, Node<T> replace, Node<T> parent): Rebalances the tree after deleting node del from tree, which was then replaced by node replace (one its children nodes); node parent points to the parent of the deleted node. Note that in the case that the node that was actually deleted from the tree was the successor of the element to be deleted (i.e., when the element to be deleted is stored at a node with two children), del will be the node containing the successor (and therefore replace will be the child node that replaced the successor, and parent is the parent of the successor.) • private void splay(Node<T> n): Perform a splay procedure starting at node n (see the previous section for the details of the algorithm). Comments and Tips • The TestHeightBalTree.java file tests the correctness your trees by making sure both the in-order and pre-order traversals of your tree matches those produced by the solution code. Keep in mind that as long as your implementation satisfies the BST property, your in-order traversals should match that of the target solution (in partic- ular, the in-order traversal should be all the elements in tree given in sorted order). A matching pre-order traversal means you’ve properly implemented the methods that modify the structure of the tree (rotations, splay, etc.).
  • 10.
    • Observe thatHeightBalancedTree is written so that all missing child links, as well the parent of the root, should point to nullNode. By default, nullNode is set to be null, but a deriving class can change this (as is the case for RedBlackTree when it defines its special “sentinel” null node that is black). Thus, all checks for null links should be for nullNode (and not for just null). • When implementing both leftRotate() and rightRotate(), be sure to properly up- date all child and parent pointers. Note that you should not try to change any pointers of nullNode (as it may be null), and also be sure to update the root when necessary. • Your implementations of insert() and delete() in SplayTree should be similar the overriden implementations of the same methods in RedBlackTree(), so be sure to use the latter as guiding examples. On a related note, the most involved methods you’ll write should be leftRotate(), rightRotate(), and splay(). If your code for the other methods begins to look intricate, you should rethink your approach. • Just something to observe: Although you aren’t required to understand the exact structure of the TestHeightBalTree.java, this is a good file to look at to see some of the benefits of structuring these classes to use inheritance. For example, using inheritance allows us to write one method that is capable of testing both types of
  • 11.
    trees. 5 Code Retrieval andSubmission As with Coding Assignment 3, the entire netbeans project is given as a .zip file on Canvas. To complete your assignment, please modify the given files (i.e., fill-in implementations for each method that currently says “write this method”). To submit, please submit the modi- fied project as a .zip file on Canvas. Evaluation Your submission will again be scored a 50 point scale. The point breakdown by category is as follows. • Overall Approach and Code Readability [10 points]: This category will be scored based on the overall structure and approach of your implementation. For exam- ple, how readable is your code? Did you include useful comments? Can I understand (with not too much effort) the approach you took for each method? • Method Implementation [20 points]: For this category, I will pick two of methods that you were asked to write for the assignment (for this particular assignment, I will grade one of the two rotation methods, as well as the splay()
  • 12.
    method) and doa more detailed evaluation of their implementations based on correctness, efficiency, and code readability. • Empirical Testing [20 point; 10 points public; 10 points private]: For this category, you will receive a grade based on tests I’ll run on your code. Half of the points will come from public tests, which are included TestHeightBalTree.java. The other ten points will come from private tests. 6 2 Week 3 Assignment Designing Lesson Plans: Evidence-Based Strategies ESE 645 Lesson Design for Students With Mild to Moderate Disabilities Mary Ware Instructor Shaneka Bell, EdD July 20, 2018
  • 13.
    Lesson Plan Content Areaor Developmental Focus: ELA Age/Grade of Children: 2 Length of Lesson: 1 hour Goal Students should be able to understand reading, written, listening comprehension as well as gain courage in peer interactions Objective · Reading comprehension and describing the main events · Listening to comprehension and be able to point out the main characters · To read a comprehension fluently and be able to understand a comprehension via listening · Be prepared to interact with the peers in solving problems together and improving the social skills. Standards Included CCSS.ELA-LITERACY.SL.2.1 Share with peer students the common topics that interested the student in their class CCSS.ELA-LITERACY.SL.2.2 Describe the primary ideas from the text that has been read aloud. CCSS.ELA-LITERACY.SL.2.3 Ask questions about the main events of the speaker to clarify comprehension, gathering of additional information as well as increase understanding of the main topic. CCSS.ELA-LITERACY.SL.2.4 Describe the story recounting the appropriate and relevant facts from the storybook, preferably by speaking loud in front of a fellow group members Materials Read; Once Upon A Time Book by Niki Daly
  • 14.
    Introduction The interest ofthe student will be sparked by producing their most exciting story books they have ever read. Each student should produce their favorite books and give a small recall of the storybook or describe the main characters in the book. The students will then be asked about the challenges or the difficulties they have encountered while reading the story books. This will provide the room for the teacher to mention the main ideas in the storybook which entails student who have difficulties in reading comprehension, peer interactions, reading slowly among others. Lesson Development: Direct Instruction Guided Practice: · Reading in small groups · Reading aloud in the class · Use peer tutoring for the students with special needs. Individualized instructions on the students who are slow in reading or learning will be applied. · The students can use the smart board and draw images or pictures that are connected to the main events from the storybook. · The student will share their understanding in groups of 2-3 fellow peers. Informal assessment · Student fluency in reading the comprehension aloud · Student ability to share the story events to the class · Student ability to speak aloud while reading the written comprehension Differentiation · Have extended time for taking the tests, completing assignments and responding to directions.
  • 15.
    · Have dailyvisual or written schedules. · The instructor should implement varying approaches in teaching the students, that is the use of visual components and modeling of tasks. · Parents and the Special education teacher should communicate daily on the progress of the student. · The student should sit in front of the classroom. · Reading comprehension sections aloud during exams or assessments. · Allow time for interaction among the students. · Emphasize on peer tutoring. · Have specially designed instructions Assessment (Practice/ Checking for Understanding) Independent practice: Collaborative groups: · Give details of the story from the beginning to the end with different partners. · Read the comprehension aloud while the other students are listening. Written Response · The student will write the story from a written comprehension · The student will write the story events from the listening comprehension · The student should recount and write the main events from the group interaction in reading the comprehension · The student should visualize the exciting part of the story and draw pictures of the main characters Closing Closing the study lesson
  • 16.
    · The studentswill share stories of the main character to the fellow peers · The student will exchange their picture with their fellow peers References English Language Arts Standards. (2018). Retrieved from http://www.corestandards.org/ELA-Literacy/ Killian, S. (2018). Top 10 Evidence Based Teaching Strategies. Retrieved from http://www.evidencebasedteaching.org.au/evidence-based- teaching-strategies/ Rubie‐Davies, C. M. (2007). Classroom interactions: Exploring the practices of high‐and low‐expectation teachers. British Journal of Educational Psychology, 77(2), 289-306. Supports, Modifications, and Accommodations for Students. (2017). Retrieved from http://www.parentcenterhub.org/repository/accommodations/#te stinG Collection/build.xml Builds, tests, and runs the project Collection.
  • 17.
    Collection/build/classes/collection/Collection.classpackage collection; publicabstractinterface Collection { publicabstractvoid insert(Object); publicabstract boolean delete(Object); publicabstract boolean contains(Object); publicabstract int getSize(); } Collection/build/classes/collection/HeightBalancedTree$Node.c lasspackage collection; publicsynchronizedclass HeightBalancedTree$Node { protected HeightBalancedTree$Node left; protected HeightBalancedTree$Node right; protected HeightBalancedTree$Node parent; protected Object data; protected void HeightBalancedTree$Node(HeightBalancedTree, HeightBalancedTree$Node, HeightBalancedTree$Node, HeightBalancedTree$Node, Object); } Collection/build/classes/collection/HeightBalancedTree.classpa ckage collection; publicabstractsynchronizedclass HeightBalancedTree implements Collection { HeightBalancedTree$Node root; int size; HeightBalancedTree$Node nullNode; protectedstaticfinal int DELETED = 0; protectedstaticfinal int REPLACED = 1; protectedstaticfinal int PARENT = 2;
  • 18.
    public void HeightBalancedTree(); protectedabstractvoid insertionFix(HeightBalancedTree$Node); protectedabstract void deletionFix(HeightBalancedTree$Node, HeightBalancedTree$Node, HeightBalancedTree$Node); public int getSize(); public boolean contains(Comparable); protected HeightBalancedTree$Node insertNode(Comparable); public java.util.ArrayList deleteNode(Comparable); protected HeightBalancedTree$Node findNode(Comparable); protected void leftRotate(HeightBalancedTree$Node); protected void rightRotate(HeightBalancedTree$Node); protected HeightBalancedTree$Node findMinNode(HeightBalancedTree$Node); protected void setParentLink(HeightBalancedTree$Node, HeightBalancedTree$Node, HeightBalancedTree$Node); public String toString(); public String inOrderString(); protected void preOrder(HeightBalancedTree$Node, java.util.ArrayList); protected void inOrder(HeightBalancedTree$Node, java.util.ArrayList); } Collection/build/classes/collection/RedBlackTree$RBNode.clas spackage collection; publicsynchronizedclass RedBlackTree$RBNode extends HeightBalancedTree$Node { protected boolean color; protected void RedBlackTree$RBNode(RedBlackTree, HeightBalancedTree$Node, HeightBalancedTree$Node, HeightBalancedTree$Node, Object, boolean); }
  • 19.
    Collection/build/classes/collection/RedBlackTree.classpackage collection; publicsynchronizedclass RedBlackTree extends HeightBalancedTree{ privatestaticfinal boolean RED = 1; privatestaticfinal boolean BLACK = 0; public void RedBlackTree(); public void insert(Comparable); public boolean delete(Comparable); protected void insertionFix(HeightBalancedTree$Node); protected void deletionFix(HeightBalancedTree$Node, HeightBalancedTree$Node, HeightBalancedTree$Node); private RedBlackTree$RBNode convertToRBNode(HeightBalancedTree$Node, boolean); } Collection/build/classes/collection/SplayTree.classpackage collection; publicsynchronizedclass SplayTree extends HeightBalancedTree { public void SplayTree(); public void insert(Comparable); public boolean delete(Comparable); protected void insertionFix(HeightBalancedTree$Node); protected void deletionFix(HeightBalancedTree$Node, HeightBalancedTree$Node, HeightBalancedTree$Node); private void splay(HeightBalancedTree$Node); } Collection/build/classes/collection/TestHeightBalTrees.classpac kage collection; publicsynchronizedclass TestHeightBalTrees {
  • 20.
    privatestaticfinal String[] INORDER; privatestaticfinalString[] ROT_PREORDER; privatestaticfinal String[] SPLAY_PREORDER; public void TestHeightBalTrees(); publicstatic int doTests(HeightBalancedTree, String[], String[]); publicstatic void testOne(HeightBalancedTree); publicstatic void testTwo(HeightBalancedTree); publicstatic void testThree(HeightBalancedTree); publicstatic void testFour(HeightBalancedTree); publicstatic void testFive(HeightBalancedTree); publicstatic void printTestMessage(HeightBalancedTree, int, int[], String[], String[]); publicstatic void main(String[]); static void <clinit>(); } Collection/manifest.mf Manifest-Version: 1.0 X-COMMENT: Main-Class will be added automatically by build Collection/nbproject/build-impl.xml
  • 26.
    Must set src.dir Mustset test.src.dir Must set build.dir Must set dist.dir Must set build.classes.dir Must set dist.javadoc.dir Must set build.test.classes.dir Must set build.test.results.dir Must set build.classes.excludes Must set dist.jar
  • 29.
  • 33.
  • 40.
    Must set JVMto use for profiling in profiler.info.jvm Must set profiler agent JVM arguments in profiler.info.jvmargs.agent
  • 46.
    Must select somefiles in the IDE or set javac.includes
  • 47.
    To run thisapplication from the command line without Ant, try: java -jar "${dist.jar.resolved}"
  • 48.
    Must select onefile in the IDE or set run.class Must select one file in the IDE or set run.class
  • 49.
    Must select onefile in the IDE or set debug.class Must select one file in the IDE or set debug.class Must set fix.includes
  • 50.
    This target onlyworks when run from inside the NetBeans IDE. Must select one file in the IDE or set profile.class This target only works when run from inside the NetBeans IDE. This target only works when run from inside the NetBeans IDE.
  • 51.
    This target onlyworks when run from inside the NetBeans IDE.
  • 52.
    Must select onefile in the IDE or set run.class Must select some files in the IDE or set test.includes Must select one file in the IDE or set run.class Must select one file in the IDE or set applet.url
  • 54.
    Must select somefiles in the IDE or set javac.includes
  • 55.
    Some tests failed;see details above. Must select some files in the IDE or set test.includes Some tests failed; see details above. Must select some files in the IDE or set test.class Must select some method in the IDE or set test.method Some tests failed; see details above. Must select one file in the IDE or set test.class Must select one file in the IDE or set test.class
  • 56.
    Must select somemethod in the IDE or set test.method Must select one file in the IDE or set applet.url Must select one file in the IDE or set applet.url
  • 58.
    Collection/nbproject/genfiles.properties build.xml.data.CRC32=a24dc44d build.xml.script.CRC32=1fd00482 [email protected] # Thisfile is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. nbproject/build-impl.xml.data.CRC32=a24dc44d nbproject/build-impl.xml.script.CRC32=f6a04097 nbproject/[email protected] Collection/nbproject/private/private.properties compile.on.save=true user.properties.file=C:UsersnbkellAppDataRoamingNetB eans8.2build.properties Collection/nbproject/private/private.xml
  • 59.
    file:/C:/Users/Nat/Box/CSC%20330%20Spring%202019/homew orks/coding-3-base/Collection/src/collection/Collection.java file:/C:/Users/Nat/Box/CSC%20330%20Spring%202019/homew orks/coding-3-base/Collection/src/collection/SplayTree.java file:/C:/Users/Nat/Box/CSC%20330%20Spring%202019/homew orks/coding-3- base/Collection/src/collection/TestHeightBalTrees.java file:/C:/Users/Nat/Box/CSC%20330%20Spring%202019/homew orks/coding-3-base/Collection/src/collection/RedBlackTree.java file:/C:/Users/Nat/Box/CSC%20330%20Spring%202019/homew orks/coding-3- base/Collection/src/collection/HeightBalancedTree.java Collection/nbproject/project.properties annotation.processing.enabled=true annotation.processing.enabled.in.editor=false annotation.processing.processor.options= annotation.processing.processors.list= annotation.processing.run.all.processors=true annotation.processing.source.output=${build.generated.sources. dir}/ap-source-output
  • 60.
    build.classes.dir=${build.dir}/classes build.classes.excludes=**/*.java,**/*.form # This directoryis removed when the project is cleaned: build.dir=build build.generated.dir=${build.dir}/generated build.generated.sources.dir=${build.dir}/generated-sources # Only compile against the classpath explicitly listed here: build.sysclasspath=ignore build.test.classes.dir=${build.dir}/test/classes build.test.results.dir=${build.dir}/test/results # Uncomment to specify the preferred debugger connection transport: #debug.transport=dt_socket debug.classpath= ${run.classpath} debug.test.classpath= ${run.test.classpath} # Files in build.classes.dir which should be excluded from distribution jar
  • 61.
    dist.archive.excludes= # This directoryis removed when the project is cleaned: dist.dir=dist dist.jar=${dist.dir}/Collection.jar dist.javadoc.dir=${dist.dir}/javadoc excludes= includes=** jar.compress=false javac.classpath= # Space-separated list of extra javac options javac.compilerargs= javac.deprecation=false javac.external.vm=true javac.processorpath= ${javac.classpath} javac.source=1.8 javac.target=1.8 javac.test.classpath=
  • 62.
  • 63.
    mkdist.disabled=false platform.active=default_platform run.classpath= ${javac.classpath}: ${build.classes.dir} # Space-separated listof JVM arguments used when running the project. # You may also define separate properties like run-sys- prop.name=value instead of -Dname=value. # To set system properties for unit tests define test-sys- prop.name=value: run.jvmargs= run.test.classpath= ${javac.test.classpath}: ${build.test.classes.dir} source.encoding=UTF-8 src.dir=src test.src.dir=test
  • 64.
    Collection/nbproject/project.xml org.netbeans.modules.java.j2seproject Collection Collection/src/collection/Collection.javaCollection/src/collectio n/Collection.javapackage collection; /** * Interfacefor a collection class. * Coding Assignment 3, CSC 330, Spring 2019 * (Note there is nothing in this file for you to change). * @author Nathaniel Kell * @param <T> type of objects in the collection. */ publicinterfaceCollection<T>{ /** * Insert an element into the collection. * @param element: object to be inserted */ publicvoid insert(T element); /** * Delete an element from the collection.
  • 65.
    * @param element:object to be deleted * @return true if the element was deleted (false otherwise). */ publicboolean delete(T element); /** * Check if an element exists in the collection. * @param element: object to be checked for containment. * @return true if the element exists in the collection (false o therwise). */ publicboolean contains(T element); /** * Returns the number of elements in the collection. * @return size of the collection. */ publicint getSize(); } Collection/src/collection/HeightBalancedTree.javaCollection/sr c/collection/HeightBalancedTree.javapackage collection; import java.util.*; /** * Abstract class for height balancing trees to extend from. * Coding Assignment 3, CSC 330, Spring 2019 * @author *YOUR NAME HERE* * @param <T> type of objects in the tree. */ publicabstractclassHeightBalancedTree<T extendsComparable< T>>implementsCollection<T>{
  • 66.
    Node root; int size; NodenullNode;// node to serve as null pointer /* Indices for the nodes returned by deleteNode() */ protectedfinalstaticint DELETED =0; protectedfinalstaticint REPLACED =1; protectedfinalstaticint PARENT =2; /* Node class used for storing the structure of the tree */ protectedclassNode<T>{ protectedNode left, right, parent; protected T data; protectedNode(Node l,Node r,Node p , T d){ left = l; right = r; parent = p; data = d; } } /* Construct an emepty height balancing tree */ publicHeightBalancedTree(){ size =0; nullNode =null; root = nullNode; } /** * Balances the tree after an insertion (starting at node n). * @param n : node where balancing procedure begins */ protectedabstractvoid insertionFix(Node<T> n); /**
  • 67.
    * Balances thetree after a deletion. * @param del : node that was just deleted from the tree. * @param replace: node that took the place del in the tree. * @param parent: parent of del. */ protectedabstractvoid deletionFix(Node<T> del,Node<T> replac e,Node<T> parent); @Override publicint getSize(){ return size; } @Override publicboolean contains(T element){ return findNode(element)!= nullNode; } /** * Insert a new node into the tree and return the newly constr ucted node. * @param element : element to be inserted into the tree. * @return : newly inserted node. */ protectedNode<T> insertNode(T element){ Node<T> current = root; Node<T> par = nullNode; boolean left =false;// whether we take left or right links /* Find the correct location to insert */ while(current != nullNode){ par = current; if(current.data.compareTo(element)>=0){ current = current.left; left =true; }
  • 68.
    else{ current = current.right; left=false; } } Node<T> newNode =newNode(nullNode, nullNode, par, elemen t); /* Check if new node is the root */ if(par == nullNode) root = newNode; /* Set up parent links */ elseif(left ==true) par.left = newNode; else par.right = newNode; return newNode; } /** * Deletes a node from the tree with data equal to element. * @param element : element to be deleted from the tree. * @return an array list that contains the node deleted, the no de * that replaced it, and the parent of the deleted node. */ publicArrayList<Node<T>> deleteNode(T element){ Node<T> del = findNode(element); Node<T> replace = nullNode; Node<T> parent = nullNode; ArrayList<Node<T>> ret =newArrayList(); ret.add(del); ret.add(replace);
  • 69.
    ret.add(parent); /* The nodedoes not exist in the tree */ if(del != nullNode){ /* Case 1: left is null */ if(del.left == nullNode){ replace = del.right; setParentLink(del.parent, del, del.right); } /* Case 2: right is null */ elseif(del.right == nullNode){ replace = del.left; setParentLink(del.parent, del, del.left); } /* Case 4: two children */ else{ Node<T> successor = findMinNode(del.right); del.data = successor.data; setParentLink(successor.parent, successor, successor. right); /* In this case, we've deleteed successor, and its right child has taken its place */ del = successor; replace = del.right; } ret.set(DELETED,del); ret.set(REPLACED,replace); ret.set(PARENT, del.parent); } return ret; } /** * Searches for and returns a node with data equal to element.
  • 70.
    * @param element:method finds a node with data equal to e lement. * @return node that has data equal to element. */ protectedNode<T> findNode(T element){ Node<T> current = root; while(current != nullNode){ if(current.data.equals(element)) return current; elseif(current.data.compareTo(element)>=0) current = current.left; else current = current.right; } return nullNode; } /** * Perform a left rotation on the subtree rooted at rotRoot. * @param rotRoot: root of the subtree to be rotated. */ protectedvoid leftRotate(Node rotRoot){ /** * * *** WRITE THIS METHOD *** * * **/ } /** * Perform a right rotation on the subtree rooted at rotRoot. * @param rotRoot: root of the subtree to be rotated. */
  • 71.
    protectedvoid rightRotate(Node rotRoot){ /** * * ***WRITE THIS METHOD *** * * **/ } /** * Find the minimum node the subtree rooted at node n. * @param n : starting node of the search * @return node with minimum value in the subtree rooted at n. */ protectedNode<T> findMinNode(Node<T> n){ Node<T> cur = n; while(cur.left != nullNode) cur = cur.left; return cur; } /** * Replaces parent's child pointer to child with newChild. * @param par : node to replace child link. * @param child : original child of parent. * @param newChild : new child of parent. */ protectedvoid setParentLink(Node<T> par,Node<T> child,Node <T> newChild){ if(newChild != nullNode) newChild.parent = par; if(par != nullNode){ if(child == par.left) par.left = newChild;
  • 72.
    else par.right = newChild; } else root= newChild; } /** * Return the pre-order representation of the tree * @return string containing the pre- order sequence of the tree. */ @Override publicString toString(){ ArrayList<String> stringList =newArrayList(); preOrder(root, stringList); String treeString =""; for(int i =0; i < stringList.size()-1; i++) treeString += stringList.get(i)+", "; treeString += stringList.get(stringList.size()-1); return treeString; } /** * Return the in-order representation of the tree * @return string containing the in- order sequence of the tree. */ publicString inOrderString(){ ArrayList<String> stringList =newArrayList(); inOrder(root, stringList); String treeString =""; for(int i =0; i < stringList.size()-1; i++)
  • 73.
    treeString += stringList.get(i)+","; treeString += stringList.get(stringList.size()-1); return treeString; } /** * Recursively perform an in-order traversal or the tree. * @param cur : current node of the traversal. * @param stringList : string that will contain the sequence a t the end of search. */ protectedvoid preOrder(Node<T> cur,ArrayList<String> stringL ist){ if(cur != nullNode){ stringList.add(cur.data.toString()); preOrder(cur.left, stringList); preOrder(cur.right, stringList); } } /** * Recursively perform an in-order traversal or the tree. * @param cur : current node of the traversal. * @param stringList : string that will contain the sequence a t the end of search. */ protectedvoid inOrder(Node<T> cur,ArrayList<String> stringLi st){ if(cur != nullNode){ inOrder(cur.left, stringList); stringList.add(cur.data.toString()); inOrder(cur.right, stringList); } }
  • 74.
    } Collection/src/collection/RedBlackTree.javaCollection/src/colle ction/RedBlackTree.javapackage collection; import java.util.ArrayList; /** *Implementation of a red-black tree. * Coding Assignment 3, CSC 330, Spring 2019 * (Note there is nothing in this file for you to change) * @author Nathaniel Kell * @param <T> type of objects in the tree. */ publicclassRedBlackTree<T extendsComparable<T>>extendsHe ightBalancedTree<T>{ /* boolean values corresponding to red and black. */ privatestaticfinalboolean RED =true; privatestaticfinalboolean BLACK =false; /* Modified node class that now has a color value */ protectedclassRBNode<T>extendsNode<T>{ protectedboolean color; protectedRBNode(Node l,Node r,Node p , T d,boolean c){ super(l, r, p, d); color = c; } } /* Construct an empty red-black tree */ publicRedBlackTree(){ super(); nullNode =newRBNode(null,null,null,null, BLACK);
  • 75.
    nullNode.parent = nullNode; nullNode.left= nullNode; nullNode.right = nullNode; root = nullNode; } @Override publicvoid insert(T element){ Node<T> newNode = insertNode(element); RBNode<T>RBnewNode= convertToRBNode(newNode, RED); if(((RBNode)RBnewNode.parent).color == RED) insertionFix(RBnewNode); ((RBNode)root).color = BLACK; size++; } @Override publicboolean delete(T element){ ArrayList<Node<T>> delNodes = deleteNode(element); Node<T> del = delNodes.get(DELETED); Node<T> replace = delNodes.get(REPLACED); Node<T> parent = delNodes.get(PARENT); if(del == nullNode) returnfalse; if(((RBNode)del).color == BLACK) deletionFix(del, replace, parent); size--; returntrue; } @Override
  • 76.
    protectedvoid insertionFix(Node<T> n){ RBNodecur =(RBNode)n; while(((RBNode)cur.parent).color == RED){ RBNode grandparent =(RBNode)cur.parent.parent; /* Meta case 1: cur's parent is a left child of its parent */ if(cur.parent == grandparent.left){ RBNode aunt =(RBNode)grandparent.right; /* Case 1: cur's aunt is red */ if(aunt.color == RED){ ((RBNode)cur.parent).color = BLACK; aunt.color = BLACK; grandparent.color = RED; cur = grandparent; } else{ /* Case 2: aunt is black and cur is a right child */ if(cur == cur.parent.right){ leftRotate((cur.parent)); cur =(RBNode)cur.left; } /* Case 3: aunt is black and cur is a left child */ ((RBNode)cur.parent).color = BLACK; grandparent.color = RED; rightRotate(grandparent); } } /* Meta case 2: cur's parent is a right child of its parent * (each subcase are symmetric to those of meta- case 1) */ else{ RBNode aunt =(RBNode)grandparent.left; if(aunt.color == RED){ ((RBNode)cur.parent).color = BLACK;
  • 77.
    aunt.color = BLACK; grandparent.color= RED; cur = grandparent; } else{ if(cur == cur.parent.left){ rightRotate((cur.parent)); cur =(RBNode)cur.right; } ((RBNode)cur.parent).color = BLACK; grandparent.color = RED; leftRotate(grandparent); } } }// end while } @Override protectedvoid deletionFix(Node<T> del,Node<T> replace,Node <T> parent){ RBNode<T> cur =(RBNode)replace; while(cur != root && cur.color == BLACK){ RBNode<T> par =(RBNode)cur.parent; if(cur == nullNode) par =(RBNode)parent; /* Meta-case 1: cure is a left child */ if(cur == par.left){ RBNode<T> sibling =(RBNode)par.right; /* Case 1: cur's sibling is red */ if(sibling.color == RED){ sibling.color = BLACK; par.color = RED; leftRotate(par); sibling =(RBNode)par.right; } /* Case 2: cur's sibling is black and sibling's children are both b
  • 78.
    lack */ if(((RBNode)sibling.left).color ==BLACK &&((RBNode)siblin g.right).color == BLACK){ sibling.color = RED; cur = par; } /* Case 3: cur's sibling is black and just sibling's right child is b lack */ else{ if(((RBNode)sibling.right).color == BLACK){ ((RBNode)sibling.left).color = BLACK; sibling.color = RED; rightRotate(sibling); sibling =(RBNode)par.right; } /* Case 4: cur's sibling is black and sibling's left child is red */ sibling.color = par.color; par.color = BLACK; ((RBNode)sibling.right).color = BLACK; leftRotate(par); cur =(RBNode)root; } } /* Meta-case 2: cur is a right child * (subcases are symmetric to those of meta-case 1) */ else{ RBNode<T> sibling =(RBNode)par.left; if(sibling.color == RED){ sibling.color = BLACK; par.color = RED; rightRotate(par); sibling =(RBNode)par.left; } if(((RBNode)sibling.left).color == BLACK &&((RBNode)siblin g.right).color == BLACK){
  • 79.
    sibling.color = RED; cur= par; } else{ if(((RBNode)sibling.left).color == BLACK){ ((RBNode)sibling.right).color = BLACK; sibling.color = RED; leftRotate(sibling); sibling =(RBNode)par.left; } sibling.color = par.color; par.color = BLACK; ((RBNode)sibling.left).color = BLACK; rightRotate(par); cur =(RBNode)root; } } }// end while cur.color = BLACK; } /** * Convert a standard node into a red- black node (where the the RBnode * replaces the standard node in the tree with respect to its lin ks). * @param n : standard node to be converted. * @param c : color of the red-black node * @return converted RBNode. */ privateRBNode<T> convertToRBNode(Node<T> n,boolean c){ RBNode<T> rbN =newRBNode(n.left, n.right, n.parent, n.data, c); if(rbN.parent == nullNode) root = rbN; elseif(rbN.parent.left == n)
  • 80.
    rbN.parent.left =(Node)rbN; else rbN.parent.right =(Node)rbN; returnrbN; } } Collection/src/collection/SplayTree.javaCollection/src/collectio n/SplayTree.javapackage collection; importstatic collection.HeightBalancedTree.DELETED; import java.util.ArrayList; /** * SplayTree height balancing tree class. * Coding Assignment 3, CSC 330, Spring 2019 * @author *YOUR NAME HERE* * @param <T> type of objects in the tree. */ publicclassSplayTree<T extendsComparable<T>>extendsHeight BalancedTree<T>{ /* Construct an empty splay tree*/ publicSplayTree(){ super(); } @Override publicvoid insert(T element){ /** * * *** WRITE THIS METHOD *** *
  • 81.
    * **/ } @Override publicboolean delete(T element){ /** * * ***WRITE THIS METHOD *** * * **/ } @Override protectedvoid insertionFix(Node<T> n){ /** * * *** WRITE THIS METHOD *** * * **/ } @Override protectedvoid deletionFix(Node<T> del,Node<T> replace,Node <T> parent){ /** * * *** WRITE THIS METHOD *** * * **/
  • 82.
    } /** * Splay anode to the root of the tree. * @param n : node to be splayed to the top of the tree */ privatevoid splay(Node<T> n){ /** * * *** WRITE THIS METHOD *** * * **/ } } Collection/src/collection/TestHeightBalTrees.javaCollection/src /collection/TestHeightBalTrees.javapackage collection; /** * Coding Assignment 3, CSC 330, Spring 2019 * (Note there is nothing in this file for you to change). * @author Nathaniel Kell */ publicclassTestHeightBalTrees{ privatestaticfinalString[] INORDER = { "80, 90, 100", "20, 30, 35, 40, 45, 50, 60, 70, 75, 80, 90, 100", "20, 30, 35, 40, 45, 50, 60, 70, 75, 80, 85, 90, 100, 110, 120, 13 0, 140, 150", "1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 30, 35, 40, 45, 50, 60, 70, 75, 80, 85
  • 83.
    , 90, 100,110, 120, 130, 140, 150, 200, 210, 220, 230, 240, 250 ", "2, 5, 6, 8, 9, 20, 30, 35, 70, 85, 100, 120, 130, 150, 220, 230, 2 40", }; privatestaticfinalString[] ROT_PREORDER = { "90, 80, 100", "75, 45, 35, 30, 20, 40, 60, 50, 70, 90, 80, 100", "75, 45, 35, 30, 20, 40, 60, 50, 70, 110, 90, 80, 85, 100, 130, 12 0, 140, 150", "110, 45, 20, 6, 4, 2, 1, 3, 5, 8, 7, 9, 35, 30, 40, 75, 60, 50, 70, 9 0, 80, 85, 100, 150, 130, 120, 140, 210, 200, 230, 220, 240, 250 ", "70, 6, 2, 5, 20, 8, 9, 35, 30, 120, 85, 100, 220, 150, 130, 240, 2 30" }; privatestaticfinalString[] SPLAY_PREORDER = { "80, 90, 100", "20, 30, 35, 40, 45, 50, 60, 70, 75, 80, 90, 100", "85, 30, 20, 50, 40, 35, 45, 80, 70, 60, 75, 140, 120, 110, 90, 10 0, 130, 150", "1, 2, 3, 4, 5, 6, 7, 8, 9, 250, 230, 210, 85, 20, 30, 50, 40, 35, 45 , 80, 70, 60, 75, 200, 150, 140, 120, 110, 90, 100, 130, 220, 240 ", "120, 9, 5, 2, 8, 6, 70, 30, 20, 35, 85, 100, 150, 130, 230, 220, 2 40", }; publicstaticint doTests(HeightBalancedTree<Integer> tree,Strin g[] inorderStrings,String[] preOrderStrings){ int[] totalCorrect ={0};
  • 84.
    int testNumber =1; /*Test 1 */ testOne(tree); printTestMessage(tree, testNumber, totalCorrect, inorderSt rings, preOrderStrings); testNumber++; /* Test 2 */ testTwo(tree); printTestMessage(tree, testNumber, totalCorrect, inorderSt rings, preOrderStrings); testNumber++; /* Test 3 */ testThree(tree); printTestMessage(tree, testNumber, totalCorrect, inorderSt rings, preOrderStrings); testNumber++; /* Test 4 */ testFour(tree); printTestMessage(tree, testNumber, totalCorrect, inorderSt rings, preOrderStrings); testNumber++; /* Test 5 */ testFive(tree); printTestMessage(tree, testNumber, totalCorrect, inorderSt rings, preOrderStrings); return totalCorrect[0]; } /* Modify the tree for test 1 */
  • 85.
    publicstaticvoid testOne(HeightBalancedTree<Integer> tree){ tree.insert(100); tree.insert(90); tree.insert(80); } /*Modify the tree for test 2 */ publicstaticvoid testTwo(HeightBalancedTree<Integer> tree){ tree.insert(70); tree.insert(75); tree.insert(60); tree.insert(50); tree.insert(45); tree.insert(40); tree.insert(30); tree.insert(35); tree.insert(20); } /* Modify the tree for test 3 */ publicstaticvoid testThree(HeightBalancedTree<Integer> tree){ tree.insert(110); tree.insert(120); tree.insert(130); tree.insert(140); tree.insert(150); tree.insert(85); } /* Modify the tree for test 4 */ publicstaticvoid testFour(HeightBalancedTree<Integer> tree){ tree.insert(200); tree.insert(210); tree.insert(220); tree.insert(230); tree.insert(240);
  • 86.
    tree.insert(250); tree.insert(9); tree.insert(8); tree.insert(7); tree.insert(6); tree.insert(5); tree.insert(4); tree.insert(3); tree.insert(2); tree.insert(1); } /* Modify thetree for test 5 */ publicstaticvoid testFive(HeightBalancedTree<Integer> tree){ tree.delete(80); tree.delete(110); tree.delete(60); tree.delete(40); tree.delete(90); tree.delete(140); tree.delete(75); tree.delete(45); tree.delete(200); tree.delete(210); tree.delete(250); tree.delete(7); tree.delete(4); tree.delete(3); tree.delete(1); tree.delete(50); } /* Print test results of a test */ publicstaticvoid printTestMessage(HeightBalancedTree<Integer > tree, int tNum,int[] totalCorrect,String[] inOrderTests,String[] preOr
  • 87.
    derTests){ System.out.printf("Test Number: %dn",tNum); System.out.printf("Target in-order sequence: %sn" +"Produced in-order sequence: %sn" +"Target pre-order sequence: %sn" +"Produced pre-order sequence: %sn", inOrderTests[tNum- 1], tree.inOrderString(), preOrderTests[tNum- 1], tree.toString()); if(inOrderTests[tNum- 1].equals(tree.inOrderString())&& preOrderTests[tNum- 1].equals(tree.toString())){ System.out.println("*** CORRECT ***n"); totalCorrect[0]++; } else System.out.println("*** INCORRECT ***n"); } /** * @param args the command line arguments */ publicstaticvoid main(String[] args){ /* Rotation tests.*/ System.out.println("n**** ROTATION TESTS *****"); RedBlackTree<Integer> tree =newRedBlackTree(); int totalRotCorrect = doTests(tree, INORDER, ROT_PREORDE R); System.out.printf("Total Rotation Tests Correct: %dn", totalRo tCorrect); /* SplayTreee tests */ System.out.println("n-nn**** SPLAY TREE TESTS *****"); SplayTree<Integer> sTree =newSplayTree(); int totalSplayCorrect = doTests(sTree, INORDER, SPLAY_PR
  • 88.
    EORDER); System.out.printf("Total Splay TreeTayTrests Correct: %dn", t otalSplayCorrect); /* Total correct.*/ System.out.printf("nTotal Overall Correct: %dn", totalRotCorr ect + totalSplayCorrect); } }