IMPLEMENTING BAG ADT WITH BINARY SEARCH TREE
Bag ADT is same as before. Will call the new class IntTreeBag to distinguish it.
Here is the list of IntTreeBag instance variables (private) and methods (public):
IntBTNode root;
IntTreeBag()
void add(int element)
void addAll(IntTreeBag addend)
Object clone()
int countOccurrences(int target)
boolean remove(int target)
int size()
static IntTreeBag union(IntTreeBag b1,IntTreeBag b2)
Goal: implement IntTreeBag methods using IntBTNode methods when feasible.
For reference, IntBTNode documentation is stored in Lab 8 folder.
Consider implementation of IntLinkedBag methods: countOccurrences, add, remove.
countOccurrences:
Starting a root, descend through tree until dead-end (null node). At each node, compare target value to node's data. If target is less, continue descent down left subtree. If target is greater, continue descent down right subtree. If target is equal, increment counter and continue descent down left (using textbook definition of BST) subtree.
Consider recursive vs. iterative method. Develop iterative method.
add:
new node will always be added as leaf. Descend tree until spot is found, then link it in. The solution shown here (and described in textbook) is iterative, not recursive. Compare to lab 8.
// Used by driver program but not used to implement remove method. // Note this is an iterative method. public void add(int element) { IntBTNode cursor = root; boolean placed = false; IntBTNode newNode = new IntBTNode(element, null, null); if (root == null) root = newNode; else while (!placed) if (element <= cursor.getData()) if (cursor.getLeft()==null) { cursor.setLeft(newNode); placed = true; } else cursor = cursor.getLeft(); else if (cursor.getRight()==null) { cursor.setRight(newNode); placed = true; } else cursor = cursor.getRight(); }
remove:
Need to first search for the target, then consider four possible removal situations (see pages 469-470).
[ Lectures | CSC 132 | Peter Sanderson | Computer Science | SMSU ]
Last reviewed: 15 November 2000
Peter Sanderson (
PeteSanderson@smsu.edu )