Você está na página 1de 28

Chapter 10: Non-linear Data Structures

Solutions
Multiple Choice
Solutions
1. e
2. b
3. b
4. d
5. c
6. a
7. c
8. a
9. d
10. d

True/False
Solutions
1. F
2. T
3. T
4. F
5. F
6. T
7. T
8. T
9. F
10. T

Short Answer Solutions


10.1.

In Figure 10.26, list the parent, children, and siblings, if any, of the following nodes:
A
Parent: D
Children: R
Siblings: Q

B
Parent: Q
Children: S
Siblings: P

D
Parent: none
Children: A, Q
Siblings: none

R
Parent: A
Children: M, T
Siblings: none

S
Parent: B

2007 Pearson Education

S 244

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

S 245

Children: none
Siblings: none

10.2.

Identify the root and the leaves in the tree in Figure 10.26.
Root: D
Leaves: M, T, S, W

10.3.

List the nodes in Figure 10.26 using a preorder, an inorder, and a postorder traversal.
Preorder:
Inorder:

D
M

Postorder:

10.4.

R
M

R
T

M
A

T
D

Q
B

B
S

S
Q

P
P

W
W

List the nodes in Figure 10.27 using a preorder, an inorder, and a postorder traversal.
Preorder:
Inorder:

15
23

Postorder:

10.5.

7
7

23

23
49

49

14
14

49
3

14

15
7

19
61

72

61
72

61

72
19
11

38
8

38

38

11
11

19

15

Draw an expression tree for each of the following expressions.


3 + (2 * 14) 5
20 * (10 5)
20 * 10 5
(17 % 5) * 11 + 3
(5 + 3 + 2) / 4

10.6.

Draw a binary tree where each node contains a letter and


an inorder traversal spells hello
a preorder traversal spells computer
a postorder traversal spells binary

10.7.

In the binary search tree in Figure 10.28, list in order the nodes that would be visited when searching for these
numbers.
12
12

15

2007 Pearson Education

S 246

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

12

21

15

40
12

21

30

40

3
12

9
12

11

11
12

10.8.

11

In Figure 10.28, show where the following elements would be inserted in the tree.
10
as the right child of 9

1
as the left child of 3

50
as the right child of 40

31
as the left child of 40

16
as the left child of 20

17
as the left child of 20

10.9.

Show what the tree in Figure 10.28 would look like if each of these six elements were deleted.
9

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

S 247

11
15
21
30
12

10.10.

Numbers are added to a binary search tree in the order given. Draw the resulting tree.
3, 14, 5, 26, 17
50, 60, 30, 80, 70, 10, 40
1, 2, 3, 4, 5, 6
10, 9, 8, 7, 6, 5

10.11.

When a node in a binary search tree is deleted, we replace it with its inorder successor. Instead, could we
replace the deleted node with its inorder predecessor, that is, the largest element in its left subtree? If so,
repeat exercise 10.9 using this method. If not, explain why not.
Yes, we could because the inorder predecessor will also maintain the
property that all nodes in the left subtree are smaller than it and
all nodes in the right subtree are larger than it.

10.12.

Draw a five node binary tree that is a heap. Draw one that is not a heap because it is not complete. Draw one
that is complete but is still not a heap.

10.13.

Show what the heap in Figure 10.29 will look like after each of the following elements is added to it.
15
41
7
4
22
1

10.14.

Show what the heap in Figure 10.29 will look like after each of the following elements is deleted.
11
33
14
25
12
3

2007 Pearson Education

S 248

10.15.

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

Perform a heapsort on each of the following list of numbers. Draw the heap for each step in the process.
8, 14, 15, 3, 7
1, 2, 3, 4, 5
5, 4, 3, 2, 1

10.16.

Show how the heap in Figure 10.29 would look if it were stored in an array.

10.17.

12

23

14

33

40

25

20

32

11

Suppose we have a hashtable of size 7 that stores integers using the hash function f(n) = n % 7. The hashtable
handles collisions using chaining. For each sequence of integers, show what the hashtable will look like after
the elements have been added.
19, 8, 59, 40, 71
0

59

19

71

40

28, 13, 9, 7, 5, 16, 55


0

28

16

2007 Pearson Education

13

55

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

S 249

78, 12, 65, 45, 23, 7


0

78

65

45

12

23

10.18.

Repeat Exercise 10.17 with a hashtable that uses linear probing to handle collisions.

19, 8, 59, 40, 71


8
0

71

59

19

40

28, 13, 9, 7, 5, 16, 55


28
0

7
1

9
2

16

55

13

78, 12, 65, 45, 23, 7


7

78

65

45

23

12

2007 Pearson Education

S 250

10.19.

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

Repeat Exercise 10.17 with a hashtable of size 9 using the hash function f(n) = n % 9 and chaining to handle
collisions.
19, 8, 59, 40, 71
0

19

40

59

71

28, 13, 9, 7, 5, 16, 55


0

28

13

55

c.

16

78, 12, 65, 45, 23, 7

45

2007 Pearson Education

65

12

23

78

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

10.20.

S 251

Repeat Exercise 10.17 with a hashtable of size 9 using the hash function f(n) = n % 9 and linear probing to
handle collisions.

19, 8, 59, 40, 71


0

71

19

40

59

8
8

28, 13, 9, 7, 5, 16, 55


0

28

55

13

7
7

8
16

78, 12, 65, 45, 23, 7


0

45

65

12

23

78

Programming Project Solutions


10.1 ArrayListSet
//********************************************************************
// ArrayListSet.java
Author: Lewis/Loftus/Cocking
//
// An implementation of a set using an ArrayList.
//********************************************************************
import
import
import
import

java.util.Set;
java.util.ArrayList;
java.util.Iterator;
java.util.Collection;

public class ArrayListSet implements Set


{
private ArrayList set;
//----------------------------------------------------------------// Initializes this to the empty set
//----------------------------------------------------------------public ArrayListSet ()
{

2007 Pearson Education

S 252

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

set = new ArrayList();


}
//----------------------------------------------------------------// Adds the given element to the set if it is not already there.
// Returns true if the element was added.
//----------------------------------------------------------------public boolean add (Object obj)
{
if (contains(obj))
return false;
else
{
set.add(obj);
return true;
}
}
//----------------------------------------------------------------// Returns true if this set contains the given element.
//----------------------------------------------------------------public boolean contains (Object obj)
{
// Note: the ArrayList class has a contains method but it is
// not part of the AP subset
int k = 0;
while (k < set.size() && !set.get(k).equals(obj))
k++;
return (k < set.size());
}
//----------------------------------------------------------------// Returns an iterator containing the elements in this set.
//----------------------------------------------------------------public Iterator iterator ()
{
return set.iterator();
}
//----------------------------------------------------------------// Removes the given element if it exists. Returns true if
// this set contained the element.
//----------------------------------------------------------------public boolean remove (Object obj)
{
int k = 0;
while (k < set.size() && !set.get(k).equals(obj))
k++;
if (k < set.size())
{
set.remove(k);
return true;
}
else
return false;
}

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

S 253

//----------------------------------------------------------------// Returns the number of elements in this set.


//----------------------------------------------------------------public int size ()
{
return set.size();
}
//----------------------------------------------------------------// The rest of these methods below are part of the Set interface
// and therefore must be implemented, but they are not part of
// the AP subset. We use the corresponding ArrayList method for
// their implementation.
//----------------------------------------------------------------public boolean isEmpty () { return set.isEmpty(); }
public Object[] toArray() { return set.toArray(); }
public Object[] toArray(Object[] a) { return set.toArray(a); }
public boolean containsAll(Collection c) { return set.containsAll(c); }
public boolean addAll(Collection c) { return set.addAll(c); }
public boolean retainAll(Collection c) { return set.retainAll(c); }
public boolean removeAll(Collection c) { return set.removeAll(c); }
public void clear() { set.clear(); }
}

10.1 SetDriver
//********************************************************************
// SetDriver.java
Author: Lewis/Loftus/Cocking
//
// Driver to test the ArrayListSet.
//********************************************************************
import java.util.Set;
import java.util.Iterator;
public class SetDriver
{
public static void main (String[] args)
{
Set set = new ArrayListSet();
String blue = "blue";
set.add(blue);
set.add("red");
set.add("green");
System.out.println("there are " + set.size() + " elements in the set:");
Iterator it = set.iterator();
while (it.hasNext())
System.out.println(it.next());
if (set.contains(blue))
System.out.println("blue is in the set");
else
System.out.println("blue is not in the set");
if (set.contains("orange"))
System.out.println("orange is in the set");
else

2007 Pearson Education

S 254

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

System.out.println("orange is not in the set");


set.remove(blue);
if (set.contains(blue))
System.out.println("now blue is in the set");
else
System.out.println("now blue is not in the set");
}
}

10.2 TreeNode
//********************************************************************
// TreeNode.java
Author: AP Committee, comments added by
//
Lewis/Loftus/Cocking
//
// A node in a binary tree.
//********************************************************************

public class TreeNode


{
private Object value;
private TreeNode left;
private TreeNode right;
//----------------------------------------------------------------// Initializes this node.
//----------------------------------------------------------------public TreeNode (Object initValue, TreeNode initLeft, TreeNode initRight)
{
value = initValue;
left = initLeft;
right = initRight;
}
//----------------------------------------------------------------// Returns the value of this node.
//----------------------------------------------------------------public Object getValue()
{
return value;
}
//----------------------------------------------------------------// Returns the left child of this node.
//----------------------------------------------------------------public TreeNode getLeft()
{
return left;
}
//----------------------------------------------------------------// Returns the right child of this node.
//----------------------------------------------------------------public TreeNode getRight()
{

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

return right;
}
//----------------------------------------------------------------// Sets the value of this node.
//----------------------------------------------------------------public void setValue(Object theNewValue)
{
value = theNewValue;
}
//----------------------------------------------------------------// Sets the left child of this node.
//----------------------------------------------------------------public void setLeft(TreeNode theNewLeft)
{
left = theNewLeft;
}
//----------------------------------------------------------------// Sets the right child of this node.
//----------------------------------------------------------------public void setRight(TreeNode theNewRight)
{
right = theNewRight;
}
}

10.2 LetterTree
//********************************************************************
// LetterTree.java
Author: Lewis/Loftus/Cocking
//
// Creates a binary tree storing letters at each node, then
// prints the letters using a postorder traversal.
//********************************************************************

public class LetterTree


{
public static void main (String[] args)
{
TreeNode h = new TreeNode("h", null, null);
TreeNode e = new TreeNode("e", null, null);
TreeNode l1 = new TreeNode("l", h, e);
TreeNode l2 = new TreeNode("l", null, null);
TreeNode o = new TreeNode("o", l1, l2);
postorder(o);
}
//----------------------------------------------------------------// Prints each item in the tree with the given root using
// a postorder traversal.
//----------------------------------------------------------------private static void postorder (TreeNode current)
{

2007 Pearson Education

S 255

S 256

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

if (current.getLeft() != null)
postorder(current.getLeft());
if (current.getRight() != null)
postorder(current.getRight());
System.out.println(current.getValue());
}
}

10.3 TreeNode
//********************************************************************
// TreeNode.java
Author: AP Committee, comments added by
//
Lewis/Loftus/Cocking
//
// A node in a binary tree.
//********************************************************************

public class TreeNode


{
private Object value;
private TreeNode left;
private TreeNode right;
//----------------------------------------------------------------// Initializes this node.
//----------------------------------------------------------------public TreeNode (Object initValue, TreeNode initLeft, TreeNode initRight)
{
value = initValue;
left = initLeft;
right = initRight;
}
//----------------------------------------------------------------// Returns the value of this node.
//----------------------------------------------------------------public Object getValue()
{
return value;
}
//----------------------------------------------------------------// Returns the left child of this node.
//----------------------------------------------------------------public TreeNode getLeft()
{
return left;
}
//----------------------------------------------------------------// Returns the right child of this node.
//----------------------------------------------------------------public TreeNode getRight()
{

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

return right;
}
//----------------------------------------------------------------// Sets the value of this node.
//----------------------------------------------------------------public void setValue(Object theNewValue)
{
value = theNewValue;
}
//----------------------------------------------------------------// Sets the left child of this node.
//----------------------------------------------------------------public void setLeft(TreeNode theNewLeft)
{
left = theNewLeft;
}
//----------------------------------------------------------------// Sets the right child of this node.
//----------------------------------------------------------------public void setRight(TreeNode theNewRight)
{
right = theNewRight;
}
}

10.3 FamilyTree
//********************************************************************
// FamilyTree.java
Author: Lewis/Loftus/Cocking
//
// Creates a binary tree representing a (fictitious) family tree
// and prints it.
//********************************************************************

public class FamilyTree


{
public static void main (String[] args)
{
TreeNode grandmam = new TreeNode("Grandma Smith", null, null);
TreeNode grandpam = new TreeNode("Grandpa Smith", null, null);
TreeNode grandmad = new TreeNode("Grandma Jones", null, null);
TreeNode grandpad = new TreeNode("Grandpa Jones", null, null);
TreeNode mom = new TreeNode("Mary Jones", grandmam, grandpam);
TreeNode dad = new TreeNode("Dave Jones", grandmad, grandpad);
TreeNode me = new TreeNode("Lisa Jones", mom, dad);
System.out.println(me.getValue() + "'s Family Tree:");
printTree(me);
}
//----------------------------------------------------------------// Prints a family tree.
//-----------------------------------------------------------------

2007 Pearson Education

S 257

S 258

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

private static void printTree (TreeNode current)


{
if (current.getLeft() != null)
{
System.out.println(current.getValue() + "'s mother: " +
current.getLeft().getValue());
printTree(current.getLeft());
}
if (current.getRight() != null)
{
System.out.println(current.getValue() + "'s father: " +
current.getRight().getValue());
printTree(current.getRight());
}
}
}

10.4 TreeNode
//********************************************************************
// TreeNode.java
Author: AP Committee, comments added by
//
Lewis/Loftus/Cocking
//
// A node in a binary tree.
//********************************************************************

public class TreeNode


{
private Object value;
private TreeNode left;
private TreeNode right;
//----------------------------------------------------------------// Initializes this node.
//----------------------------------------------------------------public TreeNode (Object initValue, TreeNode initLeft, TreeNode initRight)
{
value = initValue;
left = initLeft;
right = initRight;
}
//----------------------------------------------------------------// Returns the value of this node.
//----------------------------------------------------------------public Object getValue()
{
return value;
}
//----------------------------------------------------------------// Returns the left child of this node.
//----------------------------------------------------------------public TreeNode getLeft()
{

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

return left;
}
//----------------------------------------------------------------// Returns the right child of this node.
//----------------------------------------------------------------public TreeNode getRight()
{
return right;
}
//----------------------------------------------------------------// Sets the value of this node.
//----------------------------------------------------------------public void setValue(Object theNewValue)
{
value = theNewValue;
}
//----------------------------------------------------------------// Sets the left child of this node.
//----------------------------------------------------------------public void setLeft(TreeNode theNewLeft)
{
left = theNewLeft;
}
//----------------------------------------------------------------// Sets the right child of this node.
//----------------------------------------------------------------public void setRight(TreeNode theNewRight)
{
right = theNewRight;
}
}

10.4 ExpressionNode
//********************************************************************
// ExpressionNode.java
Author: Lewis/Loftus/Cocking
//
// A node in an expression tree. The value in a node is stored
// as a String. It can either be a string containing an integer,
// such as "23", or a string containing an operator, such as "+".
//********************************************************************
public class ExpressionNode extends TreeNode
{
//----------------------------------------------------------------// Initializes this node. The first param must be a string
// that is either an integer or an operator.
//----------------------------------------------------------------public ExpressionNode (String val, ExpressionNode left, ExpressionNode
right)
{
super(val, left, right);
}

2007 Pearson Education

S 259

S 260

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

//----------------------------------------------------------------// Returns the integer value of this node by evaluating the


// expression subtree of which this node is the root.
//----------------------------------------------------------------public int getExprValue()
{
String val = (String) getValue();
if (val.equals("+"))
return ((ExpressionNode)getLeft()).getExprValue() +
((ExpressionNode)getRight()).getExprValue();
else if (val.equals("-"))
return ((ExpressionNode)getLeft()).getExprValue() ((ExpressionNode)getRight()).getExprValue();
else if (val.equals("*"))
return ((ExpressionNode)getLeft()).getExprValue() *
((ExpressionNode)getRight()).getExprValue();
else if (val.equals("/"))
return ((ExpressionNode)getLeft()).getExprValue() /
((ExpressionNode)getRight()).getExprValue();
else if (val.equals("%"))
return ((ExpressionNode)getLeft()).getExprValue() %
((ExpressionNode)getRight()).getExprValue();
else // this node is an integer
return Integer.parseInt(val);
}
}

10.4 Evaluate
//********************************************************************
// Evaluate.java
Author: Lewis/Loftus/Cocking
//
// Builds an expression tree and evaluates it.
//********************************************************************
public class Evaluate
{
public static void main (String[] args)
{
String expr = "5 + 3 * 4 - 23 % 10";
ExpressionNode
ExpressionNode
ExpressionNode
ExpressionNode
ExpressionNode

five = new ExpressionNode("5", null, null);


three = new ExpressionNode("3", null, null);
four = new ExpressionNode("4", null, null);
twentythree = new ExpressionNode("23", null, null);
ten = new ExpressionNode("10", null, null);

ExpressionNode
ExpressionNode
ExpressionNode
ExpressionNode

times = new ExpressionNode("*", three, four);


mod = new ExpressionNode("%", twentythree, ten);
plus = new ExpressionNode("+", five, times);
minus = new ExpressionNode("-", plus, mod);

System.out.println(expr + " = " + minus.getExprValue());


}
}

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

10.5 HeapOfCharacters
//********************************************************************
// HeapOfCharacters.java
Author: Lewis/Loftus/Cocking
//
// Implements a heap of characters.
//********************************************************************
import java.util.ArrayList;
public class HeapOfCharacters
{
private ArrayList<Character> heap;
//----------------------------------------------------------------// Sets up an empty heap.
//----------------------------------------------------------------public HeapOfCharacters ()
{
heap = new ArrayList<Character>();
heap.add(null); // add a "dummy" element in position 0
}
//----------------------------------------------------------------// Returns a string representing this heap.
//----------------------------------------------------------------public String toString ()
{
return heap.toString();
}
//----------------------------------------------------------------// Adds an element to the heap.
//----------------------------------------------------------------public void add (Character ch)
{
heap.add(ch);
bubbleUp();
}
//----------------------------------------------------------------// Removes and returns the root of the heap, rearranging
// the elements to preserve the heap.
// There must be at least one element in the heap.
//----------------------------------------------------------------public Character removeRoot ()
{
Character lastChar = heap.remove(heap.size()-1);
if (heap.size() <= 1) // only the root was left (plus "dummy" null)
{
return lastChar;
}
else
{
// Replace root with last element, then bubble down
Character rootChar = heap.set(1, lastChar);
bubbleDown();
return rootChar;

2007 Pearson Education

S 261

S 262

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

}
}
//----------------------------------------------------------------// Bubbles the last element up as necessary to preserve
// the ordering of the heap.
//----------------------------------------------------------------private void bubbleUp ()
{
int curIndex = heap.size() - 1;
int parentIndex = curIndex / 2;
Character cur = heap.get(curIndex);
while ((curIndex > 1) &&
(cur.compareTo(heap.get(parentIndex)) < 0))
{
// Swap current element with its parent
Character parent = heap.get(parentIndex);
heap.set(parentIndex, cur);
heap.set(curIndex, parent);
curIndex = parentIndex;
parentIndex = curIndex / 2;
}
}
//----------------------------------------------------------------// Bubbles the first element down as necessary to preserve
// the ordering of the heap.
//----------------------------------------------------------------private void bubbleDown ()
{
int curIndex = 1;
int child1Index = curIndex * 2;
int child2Index = curIndex * 2 + 1;
int swapIndex = 1;
Character cur = heap.get(curIndex);
while ((child1Index < heap.size()) && (swapIndex > 0))
{
swapIndex = -1; // -1 = no swap
if (child2Index < heap.size())
{
Character child1 = heap.get(child1Index);
Character child2 = heap.get(child2Index);
if ((child1.compareTo(child2) <= 0) &&
(cur.compareTo(child1) > 0))
{
swapIndex = child1Index;
}
else if ((child2.compareTo(child1) < 0) &&
(cur.compareTo(child2) > 0))
{
swapIndex = child2Index;
}
}
else if (cur.compareTo(heap.get(child1Index)) > 0)

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

{
swapIndex = child1Index;
}
// Swap current element with smaller child
if (swapIndex != -1)
{
Character swapVal = heap.get(swapIndex);
heap.set(swapIndex, cur);
heap.set(curIndex, swapVal);
// Reset indices
curIndex = swapIndex;
cur = heap.get(curIndex);
child1Index = curIndex * 2;
child2Index = curIndex * 2 + 1;
}
}
}
}
10.5 HeapSort
//********************************************************************
// HeapSort.java
Author: Lewis/Loftus/Cocking
//
// Sort an array of characters using heapsort.
//********************************************************************
public class HeapSort
{
//----------------------------------------------------------------// Sorts an array of characters using heapsort.
//----------------------------------------------------------------public static void heapsort (char[] data)
{
HeapOfCharacters heap = new HeapOfCharacters();
// Add the characters to the heap.
for (char c : data)
{
heap.add(c);
}
// Remove the characters from the heap in sorted order
// and put them back into the array.
for (int i = 0; i < data.length; i++)
{
data[i] = heap.removeRoot();
}
}
public static String toStr (char[] a)
{
String s = "[";
for (char c : a)
{
s += c + ", ";

2007 Pearson Education

S 263

S 264

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

}
s = s.substring(0,s.length()-2) + "]";
return s;
}
public static void main (String[] args)
{
char[] someChars = {'e', 'r', 'i', 'q', 'z', 'y', 'd', 'm'};
System.out.println("before sorting: " + toStr(someChars));
heapsort (someChars);
System.out.println("after sorting: " + toStr(someChars));
}
}

10.6 ListNode
//********************************************************************
// ListNode.java
Author: AP Committee, comments added by
//
Lewis/Loftus/Cocking
//
// A node in a linked list
//********************************************************************

public class ListNode


{
private Object value;
private ListNode next;
//----------------------------------------------------------------// Initializes this node.
//----------------------------------------------------------------public ListNode (Object initValue, ListNode initNext)
{
value = initValue;
next = initNext;
}
//----------------------------------------------------------------// Returns the value of this node.
//----------------------------------------------------------------public Object getValue ()
{
return value;
}
//----------------------------------------------------------------// Returns the next reference in this node.
//----------------------------------------------------------------public ListNode getNext ()
{
return next;
}
//----------------------------------------------------------------// Sets the value of this node.

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

//----------------------------------------------------------------public void setValue (Object theNewValue)


{
value = theNewValue;
}
//----------------------------------------------------------------// Sets the next reference in this node.
//----------------------------------------------------------------public void setNext (ListNode theNewNext)
{
next = theNewNext;
}
}
10.6 Hashtable
//********************************************************************
// Hashtable.java
Author: Lewis/Loftus/Cocking
//
// Implements a hashtable using chaining to handle collisions.
//********************************************************************

public class Hashtable


{
private int size;
private ListNode[] table;
//----------------------------------------------------------------// Sets up an empty hashtable with the given size.
//----------------------------------------------------------------public Hashtable (int numSlots)
{
size = numSlots;
table = new ListNode[size];
}
//----------------------------------------------------------------// Adds an element to the hashtable.
//----------------------------------------------------------------public void add (Object obj)
{
// Create a node for the given element
ListNode element = new ListNode(obj, null);
// Calculate the hash code
int index = obj.hashCode() % size;
// Add the element to the appropriate cell, using chaining
if (table[index] == null)
table[index] = element;
else
{
// Chain the element to the beginning of the list
element.setNext(table[index]);
table[index] = element;
}

2007 Pearson Education

S 265

S 266

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

}
//----------------------------------------------------------------// Returns a string representation of this hashtable.
//----------------------------------------------------------------public String toString ()
{
String str = "";
for (int i=0; i < size; i++)
{
str += i + ": ";
ListNode current = table[i];
while (current != null)
{
str += current.getValue() + "
current = current.getNext();
}
str += "\n";
}

";

return str;
}
}
10.6 HashTest
//********************************************************************
// HashTest.java
Author: Lewis/Loftus/Cocking
//
// Driver for testing a hashtable.
//********************************************************************
public class HashTest
{
//----------------------------------------------------------------// Creates a hashtable of size 7, adds numbers to it, then
// prints it out.
//----------------------------------------------------------------public static void main (String[] args)
{
Hashtable table = new Hashtable(7);
table.add(new
table.add(new
table.add(new
table.add(new
table.add(new
table.add(new

Integer(36));
Integer(15));
Integer(23));
Integer(26));
Integer(5));
Integer(40));

System.out.println (table);
}
}

10.7 Book
//********************************************************************
// Book.java
Author: Lewis/Loftus/Cocking

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

//
// Represents a book
//********************************************************************
public class Book
{
private String title;
private String author;
private int pages;
//----------------------------------------------------------------// Sets up a book.
//----------------------------------------------------------------public Book (String bookTitle, String bookAuthor, int numPages)
{
title = bookTitle;
author = bookAuthor;
pages = numPages;
}
//----------------------------------------------------------------// Sets this book's author.
//----------------------------------------------------------------public void setAuthor (String bookAuthor)
{
author = bookAuthor;
}
//----------------------------------------------------------------// Sets this book's title.
//----------------------------------------------------------------public void setTitle (String bookTitle)
{
title = bookTitle;
}
//----------------------------------------------------------------// Sets this book's number of pages.
//----------------------------------------------------------------public void setPages (int numPages)
{
pages = numPages;
}
//----------------------------------------------------------------// Returns a hash code for this book.
//----------------------------------------------------------------public int hashCode ()
{
return title.length() + author.length() + pages;
}
//----------------------------------------------------------------// Returns a string representation of this book.
//----------------------------------------------------------------public String toString ()
{

2007 Pearson Education

S 267

S 268

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

return title + " by " + author + ", " + pages + " pages";
}
}
10.7 ListNode
//********************************************************************
// ListNode.java
Author: AP Committee, comments added by
//
Lewis/Loftus/Cocking
//
// A node in a linked list
//********************************************************************

public class ListNode


{
private Object value;
private ListNode next;
//----------------------------------------------------------------// Initializes this node.
//----------------------------------------------------------------public ListNode (Object initValue, ListNode initNext)
{
value = initValue;
next = initNext;
}
//----------------------------------------------------------------// Returns the value of this node.
//----------------------------------------------------------------public Object getValue ()
{
return value;
}
//----------------------------------------------------------------// Returns the next reference in this node.
//----------------------------------------------------------------public ListNode getNext ()
{
return next;
}
//----------------------------------------------------------------// Sets the value of this node.
//----------------------------------------------------------------public void setValue (Object theNewValue)
{
value = theNewValue;
}
//----------------------------------------------------------------// Sets the next reference in this node.
//----------------------------------------------------------------public void setNext (ListNode theNewNext)
{
next = theNewNext;

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

}
}
10.7 Hashtable
//********************************************************************
// Hashtable.java
Author: Lewis/Loftus/Cocking
//
// Implements a hashtable using chaining to handle collisions.
//********************************************************************

public class Hashtable


{
private int size;
private ListNode[] table;
//----------------------------------------------------------------// Sets up an empty hashtable with the given size.
//----------------------------------------------------------------public Hashtable (int numSlots)
{
size = numSlots;
table = new ListNode[size];
}
//----------------------------------------------------------------// Adds an element to the hashtable.
//----------------------------------------------------------------public void add (Object obj)
{
// Create a node for the given element
ListNode element = new ListNode(obj, null);
// Calculate the hash code
int index = obj.hashCode() % size;
// Add the element to the appropriate cell, using chaining
if (table[index] == null)
table[index] = element;
else
{
// Chain the element to the beginning of the list
element.setNext(table[index]);
table[index] = element;
}
}
//----------------------------------------------------------------// Returns a string representation of this hashtable.
//----------------------------------------------------------------public String toString ()
{
String str = "";
for (int i=0; i < size; i++)
{
str += i + ": ";

2007 Pearson Education

S 269

S 270

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

ListNode current = table[i];


while (current != null)
{
str += current.getValue() + "
current = current.getNext();
}
str += "\n";

";

}
return str;
}
}
10.7 BookHash
//********************************************************************
// BookHash.java
Author: Lewis/Loftus/Cocking
//
// Stores some books in a hashtable and prints it.
//********************************************************************
public class BookHash
{
//----------------------------------------------------------------// Creates a hashtable of size 7, adds numbers to it, then
// prints it out.
//----------------------------------------------------------------public static void main (String[] args)
{
Hashtable table = new Hashtable(11);
Book o1984 = new Book("1984", "George Orwell", 268);
Book eon = new Book("Eon", "Greg Bear", 504);
Book stranger = new Book("Stranger in a Strange Land",
"Robert A Heinlein", 525);
Book obedience = new Book("Obedience to Authority",
"Stanley Milgram", 224);
Book scape = new Book("The Scapegoat Generation", "Mike A Males", 329);
Book time = new Book("A Brief History of Time", "Stephen Hawking", 198);
table.add(o1984);
table.add(eon);
table.add(stranger);
table.add(obedience);
table.add(scape);
table.add(time);
System.out.println (table);
}
}
AP-Style Multiple Choice
Solutions
1. C
2. A
3. B

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 10 Solutions

4.
5.
6.

D
C
A

AP-Style Free Response Solution


10.1
a.
public int getHeight ()
{
return maxLevel (root, 1);
}
public int maxLevel (TreeNode node, int level)
{
if ((node.getRight() == null) && (node.getLeft() == null))
return level;
else if (node.getRight() == null)
return maxLevel (node.getLeft(), level+1);
else if (node.getLeft() == null)
return maxLevel (node.getRight(), level+1);
int maxLeft = maxLevel (node.getLeft(), level+1);
int maxRight = maxLevel (node.getRight(), level+1);
if (maxLeft > maxRight)
return maxLeft;
else
return maxRight;
}

b.
public double getAverageHeight ()
{
int totHeight = 0;
for (BinaryTree bt : trees)
{
totHeight += bt.getHeight();
}
return (double)totHeight / trees.size();
}

2007 Pearson Education

S 271

Você também pode gostar