adt - it212 web viewking saud university. college of computer & information sciences....

33
KING SAUD UNIVERSITY COLLEGE OF COMPUTER & INFORMATION SCIENCES Information Technology Department IT 212: Data Structures with JAVA ADT Specification This document is extracted from the text book: Data Structures and Abstractions with Java THIRD EDITION Frank M. Carrano Prepared by Samira Lahmar Second Semester 1427-1428/2007 Edited by Nadia Al-Ghreimil Second Semester 1430-1431 Edited by Mashael AlDuwais Second Semester 1435-1436 This copy belongs to: _______________________________ ___ NO modifications to this document are allowed. DO NOT write on this document 1

Upload: voliem

Post on 12-Feb-2018

221 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

KING SAUD UNIVERSITYCOLLEGE OF COMPUTER & INFORMATION SCIENCES

Information Technology Department

IT 212: Data Structures with JAVA

ADTSpecification

This document is extracted from the text book:

Data Structures and Abstractions with Java THIRD EDITION

Frank M. Carrano

Prepared by Samira LahmarSecond Semester 1427-1428/2007

Edited by Nadia Al-GhreimilSecond Semester 1430-1431

Edited by Mashael AlDuwaisSecond Semester 1435-1436

This copy belongs to: __________________________________

NO modifications to this document are allowed.

DO NOT write on this document anything other than your Name.

1

Page 2: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

Private Class Node

private class Node{ private T data; // entry in the sturucture private Node next; // link to next node

private Node(T dataPortion) { data = dataPortion; next = null; } // end constructor

private Node(T dataPortion, Node linkPortion) { data = dataPortion; next = linkPortion; } // end constructor

private T getData() { return data; } // end getData

private void setData(T newData) { data = newData; } // end setData

private Node getNextNode() { return next; } // end getNextNode

private void setNextNode(Node nextNode) { next = nextNode; } // end setNextNode

} // end Node

2

Page 3: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

Bag

BagInterface

/** An interface that describes the operations of a bag of objects.

public interface BagInterface < T > {

/** Gets the current number of entries in this bag. @return the integer number of entries currently in the bag */ public int getCurrentSize ();

/** Sees whether this bag is full. @return true if the bag is full, or false if not */ public boolean isFull ();

/** Sees whether this bag is empty. @return true if the bag is empty, or false if not */ public boolean isEmpty ();

/** Adds a new entry to this bag. @param newEntry the object to be added as a new entry @return true if the addition is successful, or false if not */ public boolean add (T newEntry);

/** Removes one unspecified entry from this bag, if possible. @return either the removed entry, if the removal was successful, or null */ public T remove ();

/** Removes one occurrence of a given entry from this bag, if possible.

@param anEntry the entry to be removed @return true if the removal was successful, or false if not */ public boolean remove (T anEntry);

/** Removes all entries from this bag. */ public void clear ();

/** Counts the number of times a given entry appears in this bag. @param anEntry the entry to be counted @return the number of times anEntry appears in the bag */ public int getFrequencyOf (T anEntry);

/** Tests whether this bag contains a given entry. @param anEntry the entry to locate @return true if the bag contains anEntry, or false otherwise */ public boolean contains (T anEntry);

/** Creates an array of all entries that are in this bag. @return a newly allocated array of all the entries in the bag */ public T [] toArray ();

} // end BagInterface

3

Page 4: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

Using Array to implement ADT bag

/** A class of bags whose entries are stored in a fixed-size array. public class ArrayBag < T > implements BagInterface < T > { private final T [] bag; // array of bag entriesprivate static final int DEFAULT_CAPACITY = 25;

// default size of bagprivate int numberOfEntries; //current number of entries in bag

public ArrayBag () { this(DEFAULT_INITIAL_CAPACITY);} // end default constructor

/ Implementations of the public methods declared in BagInterface go here.

// Locates a given entry within the array bag.// Returns the index of the entry, if located,// or -1 otherwise.private int getIndexOf(T anEntry) {//implementation goes here}

// Removes and returns the entry at a given index within the array bag.// If no such entry exists, returns null.private T removeEntry(int givenIndex){//implementation goes here}

} // end of class ArrayBag

A linked implementation of ADT bag

/** A class of bags whose entries are stored in a chain of linked nodes. The bag is never full. public class LinkedBag < T > implements BagInterface < T > { private Node firstNode; // reference to first node private int numberOfEntries; // current number of entries in bag

public LinkedBag () { firstNode = null; numberOfEntries = 0; } // end default constructor / Implementations of the public methods declared in BagInterface go here. private class Node // private inner class { ….} // end Node

} // end of class LinkedBag

4

Page 5: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

Stack

StackInterface

/** An interface for the ADT stack.*/

public interface StackInterface<T>{ /** Adds a new entry to the top of this stack. @param newEntry an object to be added to the stack */ public void push(T newEntry); /** Removes and returns this stackÕs top entry. @return either the object at the top of the stack or, if the stack is empty before the operation, null */ public T pop(); /** Retrieves this stackÕs top entry. @return either the object at the top of the stack or null if the stack is empty */ public T peek(); /** Detects whether this stack is empty. @return true if the stack is empty */ public boolean isEmpty(); /** Removes all entries from this stack */ public void clear();} // end StackInterface

Using array to implement ADT Stack

/** A class of stacks whose entries are stored in an array.*/public class ArrayStack<T> implements StackInterface<T>{

private T[] stack; // array of stack entriesprivate int topIndex; // index of top entry

private static final int DEFAULT_INITIAL_CAPACITY = 50;

public ArrayStack(){

this(DEFAULT_INITIAL_CAPACITY); } // end default constructor

public ArrayStack(int initialCapacity){

// the cast is safe because the new array contains null entries @SuppressWarnings("unchecked") T[] tempStack = (T[])new Object[initialCapacity]; stack = tempStack;

topIndex = -1;} // end constructor

// Implementations of public methods go here.

// Doubles the size of the array stack if it is fullprivate void ensureCapacity() {} // end ensureCapacity

} // end ArrayStack

5

Page 6: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

A linked implementation of ADT Stack

/** A class of stacks whose entries are stored in a chain of nodes.*/public class LinkedStack<T> implements StackInterface<T>{

private Node topNode; // references the first node in the chain

public LinkedStack(){

topNode = null;} // end default constructor

// Implementations of public methods go here.

private class Node{….} // end Node

} // end LinkedStack

Queue

QueueInterface

/** An interface for the ADT queue.*/

public interface QueueInterface<T>{ /* Adds a new entry to the back of this queue. @param newEntry an object to be added */ public void enqueue(T newEntry); /* Removes and returns the entry at the front of this queue. @return either the object at the front of the queue or, if the queue is empty before the operation, null */ public T dequeue(); /* Retrieves the entry at the front of this queue. @return either the object at the front of the queue or, if the queue is empty, null */ public T getFront(); /* Detects whether this queue is empty. @return true if the queue is empty, or false otherwise */ public boolean isEmpty(); /* Removes all entries from this queue. */ public void clear();} // end QueueInterface

6

Page 7: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

Using array to implement ADT Queue

/** A class that implements the ADT queue by using an expandable circular array.*/

public class ArrayQueue<T> implements QueueInterface<T>{ private T[] queue; // circular array of queue entries private int frontIndex; private int backIndex; private int NumberOfEntries; private static final int DEFAULT_INITIAL_CAPACITY = 50;

public ArrayQueue() { this(DEFAULT_INITIAL_CAPACITY); } // end default constructor

public ArrayQueue(int initialCapacity) { T[] tempQueue = (T[]) new Object[initialCapacity + 1]; queue = tempQueue; frontIndex = 0; backIndex = initialCapacity; NumberOfEntries=0; } // end constructor

// Doubles the size of the array queue if it is full private void ensureCapacity() { … } // end ensureCapacity} // end ArrayQueue

A linked implementation of ADT Queue

/** A class that implements the ADT queue by using a chain of nodes that has both head and tail references.*/public class LinkedQueue<T> implements QueueInterface<T>{ private Node firstNode; // references node at front of queue private Node lastNode; // references node at back of queue

public LinkedQueue(){

firstNode = null;lastNode = null;

} // end default constructor

private class Node{…} // end Node

} // end Linkedqueue

7

Page 8: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

Deque

DequeInterface

/** An interface for the ADT deque.*/public interface DequeInterface<T>{ public void addToFront(T newEntry); public void addToBack(T newEntry); public T removeFront(); public T removeBack(); public T getFront(); public T getBack(); public boolean isEmpty(); public void clear();} // end DequeInterface

A Doubly linked implementation of Deque

/** A class that implements the ADT deque by using a doubly linked chain of nodes.*/

public class LinkedDeque<T> implements DequeInterface<T>{ private DLNode firstNode; // references node for front of deque private DLNode lastNode; // references node for back of deque

public LinkedDeque(){

firstNode = null;

lastNode = null;} // end default constructorprivate class DLNode{

private T data; // deque entryprivate DLNode next; // link to next nodeprivate DLNode previous; // link to previous node

private DLNode(T dataPortion){

data = dataPortion;next = null;previous = null;

} // end constructor

private DLNode(DLNode previousNode, T dataPortion, DLNode nextNode)

{data = dataPortion;next = nextNode;previous = previousNode;

} // end constructor

private T getData(){

return data;} // end getData

} // end DLNode} // end LinkedDequ

8

Page 9: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

PriorityQueue

PriorityQueueInterface

/** An interface for the ADT priority queue.*/public interface PriorityQueueInterface<T extends Comparable<? super T>>{ /** Adds a new entry to this priority queue. @param newEntry an object */ public void add(T newEntry);

/** Removes and returns the item with the highest priority. @return either the object with the highest priority or, if the priority queue is empty before the operation, null */ public T remove();

/** Retrieves the item with the highest priority. @return either the object with the highest priority or, if the priority queue is empty, null */ public T peek();

/** Detects whether this priority queue is empty. @return true if the priority queue is empty, or false otherwise */ public boolean isEmpty();

/** Gets the size of this priority queue. @return the number of entries currently in the priority queue */ public int getSize();

/** Removes all entries from this priority queue */ public void clear();} // end PriorityQueueInterface

9

Page 10: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

List

ListInterface/** An interface for the ADT list. Entries in the list have positions that begin with 1.*/public interface ListInterface<T>{ /** Adds a new entry to the end of this list. Entries currently in the list are unaffected. The lists size is increased by 1. @param newEntry the object to be added as a new entry */ public void add(T newEntry); /** Adds a new entry at a specified position within this list. Entries originally at and above the specified position are at the next higher position within the list. The listÕs size is increased by 1. @param newPosition an integer that specifies the desired position of the new entry @param newEntry the object to be added as a new entry @return true if the addition is successful, or false if newPosition < 1, or newPosition > getLength() + 1 */ public boolean add(int newPosition, T newEntry); /** Removes the entry at a given position from this list. Entries originally at positions higher than the given position are at the next lower position within the list, and the list’s size is decreased by 1. @param givenPosition an integer that indicates the position of the entry to be removed @return a reference to the removed entry or null, if either the list was empty, givenPosition < 1, or

givenPosition > getLength() */ public T remove(int givenPosition); /** Removes all entries from this list. */ public void clear(); /** Replaces the entry at a given position in this list. @param givenPosition an integer that indicates the position of the entry to be replaced @param newEntry the object that will replace the entry at the position givenPosition @return true if the replacement occurs, or false if either the list is empty, givenPosition < 1, or givenPosition > getLength() */ public boolean replace(int givenPosition, T newEntry); /** Retrieves the entry at a given position in this list. @param givenPosition an integer that indicates the position of the desired entry @return a reference to the indicated entry or null, if either the list is empty, givenPosition < 1, or givenPosition > getLength() */ public T getEntry(int givenPosition); /** Sees whether this list contains a given entry. @param anEntry the object that is the desired entry @return true if the list contains anEntry, or false if not */ public boolean contains(T anEntry); /** Gets the length of this list. @return the integer number of entries currently in the list */ public int getLength(); /** Sees whether this list is empty. @return true if the list is empty, or false if not */ public boolean isEmpty(); /** Retrieves all entries that are in this list in the order in which

10

Page 11: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

they occur in the list. */ public T[] toArray(); } // end ListInterface

11

Page 12: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

Using Array to implement ADT list/** A class that implements the ADT list by using an array. The list is never full.*/public class AList<T> implements ListInterface<T>{private T[] list; // array of list entriesprivate int numberOfEntries;private static final int DEFAULT_INITIAL_CAPACITY = 25;

// public methods:public AList(){

this(DEFAULT_INITIAL_CAPACITY);} // end default constructor

public AList(int initialCapacity){ numberOfEntries = 0; // the cast is safe because the new array contains null entries @SuppressWarnings("unchecked") T[] tempList = (T[])new Object[initialCapacity]; list = tempList;} // end constructor

< Implementations of the rest of the public methods. . …..go here. > // Doubles the size of the array list if it is full. private void ensureCapacity() { … } // end ensureCapacity

/* Makes room for a new entry at newPosition. Precondition: 1 <= newPosition <= numberOfEntries + 1; where numberOfEntries is list’s length before addition. */private void makeRoom(int newPosition)

{ … } // end makeRoom// Shifts entries that are beyond the entry to be removed to the // next lower position.// Precondition: 1 <= givenPosition < numberOfEntries;// numberOfEntries is listÕs length before removal. */private void removeGap(int givenPosition){ … } // end removeGap

} // end AList

A linked implementation of ADT list

/** A linked implementation of the ADT list.*/public class LList<T> implements ListInterface<T>{private Node firstNode; // reference to first nodeprivate int numberOfEntries;

public LList(){

clear();} // end default constructor

< Implementations of the rest of the public methods. . …..go here. > // Returns a reference to the node at a given position. // Precondition: List is not empty; // 1 <= givenPosition <= numberOfEntriesprivate Node getNodeAt(int givenPosition){ … } // end getNodeAt

private class Node { … } // end Node

} // end LList

12

Page 13: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

13

Page 14: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

Sorted List

SortedListInterface/** An interface for the ADT sorted list. Entries in the list have positions that begin with 1. */public interface SortedListInterface <T extends Comparable <? super T>>{ /** Adds a new entry to this sorted list in its proper order. @param newEntry the object to be added as a new entry */ public void add(T newEntry); /** Removes a specified entry from this sorted list. @param anEntry the object to be removed @return true if anEntry was located and removed */ public boolean remove(T anEntry); /** Gets the position of an entry in this sorted list. @param anEntry the object to be found @return the position of the first or only occurrence of anEntry if it occurs in the list; otherwise returns the position where anEntry would occur in the list, but as a negative integer */ public int getPosition(T anEntry); // The following methods are described in 12.7 of Chapter 12 // as part of the ADT list: public T getEntry(int givenPosition); public boolean contains(T anEntry); public T remove(int givenPosition); public void clear(); public int getLength(); public boolean isEmpty(); public T[] toArray();

} // end SortedListInterface

A linked implementation of ADT sorted List/** A class that implements the ADT sorted list by using a chain of linked nodes. Duplicate entries are allowed.*/public class SortedLinkedList <T extends Comparable <? super T>> implements SortedListInterface<T>{ private Node firstNode; // reference to first node of chain private int numberOfEntries;

public SortedLinkedList() { firstNode = null; numberOfEntries = 0; } // end default constructor

< Implementations of the sorted list operations go here. >

/* Finds the node that is before the node that should or does contain a given entry. @param anEntry the object to be located @return either a reference to the node that is before the node that contains or should contain anEntry, or null if no prior node exists (that is, if anEntry belongs at the beginning of the list) */ private Node getNodeBefore(T anEntry) {... } // end getNodeBefore

private Node getNodeAt(int givenPosition) {… } // end getNodeAt

private class Node {… } // end class Node

14

Page 15: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

}

15

Page 16: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

A sorted List implementation that uses the ADT List

public class SortedList<T extends Comparable<? super T>> implements SortedListInterface<T>{

private ListInterface<T> list; // a list of entries

public SortedList(){

list = new LList<T>; // or: new Alist<T>

} // end default constructor…

}// end SortedLinkedList

Iterator

Iterator Interface

public interface Iterator<T>{/** Task: Detects whether the iterator has completed its traversal and

gone beyond the last entry in the collection of data.@return true if the iterator has another entry to return */public boolean hasNext();

/** Task: Retrieves the next entry in the collection and advances the iterator by one position.

@return a reference to the next entry in the iteration, if one exists@throws NoSuchElementException if the iterator had reached the end

already,ie. if hasNext() is false */public T next();

/** Task: Removes from the collection the last entry that next() returned. A subsequent call to next() will behave as it would have before the removal.

Precondition: next() has been called, and remove() has not been called since then. The collection has not been altered during the iteration except by calls to this method.

@throws IllegalStateException if next() has not been called, or if remove() was called already after the last call to next().

@throws UnsupportedOperationException if this iterator does not permit a remove operation. */

public void remove(); // Optional method

} // end Iterator

16

Page 17: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

TreeInterfacepackage TreePackage;/** An interface for the ADT tree.*/public interface TreeInterface<T>{ public T getRootData(); public int getHeight(); public int getNumberOfNodes(); public boolean isEmpty(); public void clear();} // end TreeInterface

TreeIteratorInterface

package TreePackage;import java.util.Iterator;/** An interface of iterators for the ADT tree.*/public interface TreeIteratorInterface<T>{ public Iterator<T> getPreorderIterator(); public Iterator<T> getPostorderIterator(); public Iterator<T> getInorderIterator(); public Iterator<T> getLevelOrderIterator();} // end TreeIteratorInterface

BinaryTreeInterface

package TreePackage;/** An interface for the ADT binary tree.*/public interface BinaryTreeInterface<T> extends TreeInterface<T>, TreeIteratorInterface<T>{ /** Sets an existing binary tree to a new one-node binary tree. @param rootData an object that is the data in the new trees root */ public void setTree(T rootData);

/** Sets an existing binary tree to a new binary tree. @param rootData an object that is the data in the new trees root @param leftTree the left subtree of the new tree @param rightTree the right subtree of the new tree */ public void setTree(T rootData, BinaryTreeInterface<T> leftTree, BinaryTreeInterface<T> rightTree);} // end BinaryTreeInterface

17

Page 18: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

BinaryNodeInterface

package TreePackage;/** An interface for a node in a binary tree.*/interface BinaryNodeInterface<T>{ /** Retrieves the data portion of this node. @return the object in the data portion of the node */ public T getData();

/** Sets the data portion of this node. @param newData the data object */ public void setData(T newData);

/** Retrieves the left child of this node. @return the node that is this nodeÕs left child */ public BinaryNodeInterface<T> getLeftChild();

/** Retrieves the right child of this node. @return the node that is this nodeÕs right child */ public BinaryNodeInterface<T> getRightChild();

/** Sets this nodeÕs left child to a given node. @param leftChild a node that will be the left child */ public void setLeftChild(BinaryNodeInterface<T> leftChild);

/** Sets this nodeÕs right child to a given node. @param rightChild a node that will be the right child */ public void setRightChild(BinaryNodeInterface<T> rightChild);

/** Detects whether this node has a left child. @return true if the node has a left child */ public boolean hasLeftChild();

/** Detects whether this node has a right child. @return true if the node has a right child */ public boolean hasRightChild();

/** Detects whether this node is a leaf. @return true if the node is a leaf */ public boolean isLeaf();

/** Counts the nodes in the subtree rooted at this node. @return the number of nodes in the subtree rooted at this node */ public int getNumberOfNodes();

/** Computes the height of the subtree rooted at this node. @return the height of the subtree rooted at this node */ public int getHeight();

/** Copies the subtree rooted at this node. @return the root of a copy of the subtree rooted at this node */ public BinaryNodeInterface<T> copy();} // end BinaryNodeInterface

BinaryNode

package TreePackage;/** A class that represents nodes in a binary tree.*/class BinaryNode<T> implements BinaryNodeInterface<T>, java.io.Serializable{ private T data; private BinaryNode<T> left; private BinaryNode<T> right;

18

Page 19: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

…} // end BinaryNode

19

Page 20: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

BinaryTree

package TreePackage;import java.util.Iterator;import java.util.NoSuchElementException;import StackAndQueuePackage.*;

/** A class that implements the ADT binary tree.*/public class BinaryTree<T> implements BinaryTreeInterface<T>{ private BinaryNodeInterface<T> root;

public BinaryTree() { root = null; } // end default constructor

public BinaryTree(T rootData){ root = new BinaryNode<T>(rootData);} // end constructor

public BinaryTree(T rootData, BinaryTree<T> leftTree,

BinaryTree<T> rightTree){

privateSetTree(rootData, leftTree, rightTree)} // end constructor

private void privateSetTree(T rootData, BinaryTree<T> leftTree,

BinaryTree<T> rightTree){… } // end privateSetTree

private BinaryNode<T> copyNodes() // not essential{…} // end copyNodes

protected void setRootData(T rootData){… } // end setRootData

protected void setRootNode(BinaryNodeInterface<T> rootNode){… } // end setRootNode

protected BinaryNodeInterface<T> getRootNode(){… } // end getRootNode

< Implementations of the TreeInterface go here. >< Implementations of the TreeIteratorInterface go here. >< Implementations of the BinaryTreeInterface go here. >

private class PreorderIterator implements Iterator<T>{private StackInterface<BinaryNodeInterface<T>> nodeStack;public PreorderIterator(){

nodeStack = new LinkedStack<BinaryNodeInterface<T>>();if (root != null)

nodeStack.push(root);} // end default constructor< Implementations of the IteratorInterface go here. >} // end of PreorderIterator

private class InorderIterator implements Iterator<T>{…} // end InOrderIteratorprivate class PostorderIterator implements Iterator<T>{…} // endPostOrderIteratorprivate class LevelOrderIterator implements Iterator<T>{…} // end LevelOrderIterator

20

Page 21: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

} // end BinaryTree

21

Page 22: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

SearchTreeInterfacepackage TreePackage;import java.util.Iterator;/** An interface for a search tree. */public interface SearchTreeInterface<T extends Comparable<? super T>> extends TreeInterface<T>{

/** Searches for a specific entry in this tree. @param entry an object to be found @return true if the object was found in the tree */ public boolean contains(T entry);

/** Retrieves a specific entry in this tree. @param entry an object to be found @return either the object that was found in the tree or null if no such object exists */ public T getEntry(T entry);

/** Adds a new entry to this tree. if the entry matches an object that exists in the tree already, replaces the object with the new entry. @param newEntry an object to be added to the tree @return either null if newEntry was not in the tree already, or an existing entry that matched the parameter newEntry and has been replaced in the tree */ public T add(T newEntry);

/** Removes a specific entry from this tree. @param entry an object to be removed @return either the object that was removed from the tree or null if no such object exists */ public T remove(T entry);

/** Creates an iterator that traverses all entries in this tree. @return an iterator that provides sequential and ordered access to the entries in the tree */ public Iterator<T> getInorderIterator();} // end SearchTreeInterface

BinarySearchTree

package TreePackage;import java.util.Iterator;

/** A class that implements the ADT binary search tree by extending BinaryTree - Iterative version.*/public class BinarySearchTreeI<T extends Comparable<? super T>> extends BinaryTree<T> implements SearchTreeInterface<T>{ public BinarySearchTreeI() { super(); } // end default constructor

public BinarySearchTreeI(T rootEntry) { super(); setRootNode(new BinaryNode<T>(rootEntry)); } // end constructor

public void setTree(T rootData) {… } // end setTree

public void setTree(T rootData,

22

Page 23: ADT - IT212  Web viewKING SAUD UNIVERSITY. COLLEGE OF COMPUTER & INFORMATION SCIENCES. Information Technology Department. IT. 212: Data Structures with JAVA. ADT. Specification

BinaryTreeInterface<T> leftTree, BinaryTreeInterface<T> rightTree) {… } // end setTree public T getEntry(T entry) {… } // end getEntry

public boolean contains(T entry){… } // end contains

public T add(T newEntry){… } // end add

private T addEntry(T newEntry){… } // end addEntry

public T remove(T entry){… } // end remove

// Other public methods in SearchTreeInterface are inherited from BinaryTree.

// locate node that contains a match for entryprivate NodePair findNode(T entry){… } // end findNode

// Gets the node that contains the inorder predecessor of currentNode.// Precondition: currentNode has two children private NodePair getNodeToRemove(BinaryNodeInterface<T> currentNode){… } // end getNodeToRemove

// Removes a node having at most one child. private void removeNode(

BinaryNodeInterface<T> nodeToRemove, BinaryNodeInterface<T> parentNode)

{… } // end removeNode

private class NodePair{

private BinaryNodeInterface<T> first, second;

public NodePair(){ first = null; second = null;} // end default constructor

public NodePair(BinaryNodeInterface<T> firstNode, BinaryNodeInterface<T> secondNode){ first = firstNode; second = secondNode;} // end constructor

public BinaryNodeInterface<T> getFirst(){ return first;} // end getFirst

public BinaryNodeInterface<T> getSecond(){ return second;} // end getSecond

} // end NodePair

} // end BinarySearchTreeI

23