Escolar Documentos
Profissional Documentos
Cultura Documentos
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
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
S 244
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
10.6.
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
S 246
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
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
S 248
10.15.
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
16
13
55
S 249
78
65
45
12
23
10.18.
Repeat Exercise 10.17 with a hashtable that uses linear probing to handle collisions.
71
59
19
40
7
1
9
2
16
55
13
78
65
45
23
12
S 250
10.19.
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
55
c.
16
45
65
12
23
78
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.
71
19
40
59
8
8
28
55
13
7
7
8
16
45
65
12
23
78
java.util.Set;
java.util.ArrayList;
java.util.Iterator;
java.util.Collection;
S 252
S 253
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
S 254
10.2 TreeNode
//********************************************************************
// TreeNode.java
Author: AP Committee, comments added by
//
Lewis/Loftus/Cocking
//
// A node in a binary tree.
//********************************************************************
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.
//********************************************************************
S 255
S 256
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.
//********************************************************************
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.
//********************************************************************
S 257
S 258
10.4 TreeNode
//********************************************************************
// TreeNode.java
Author: AP Committee, comments added by
//
Lewis/Loftus/Cocking
//
// A node in a binary tree.
//********************************************************************
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);
}
S 259
S 260
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
ExpressionNode
ExpressionNode
ExpressionNode
ExpressionNode
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;
S 261
S 262
}
}
//----------------------------------------------------------------// 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)
{
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 + ", ";
S 263
S 264
}
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
//********************************************************************
S 265
S 266
}
//----------------------------------------------------------------// 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
//
// 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 ()
{
S 267
S 268
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
//********************************************************************
}
}
10.7 Hashtable
//********************************************************************
// Hashtable.java
Author: Lewis/Loftus/Cocking
//
// Implements a hashtable using chaining to handle collisions.
//********************************************************************
S 269
S 270
";
}
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
4.
5.
6.
D
C
A
b.
public double getAverageHeight ()
{
int totHeight = 0;
for (BinaryTree bt : trees)
{
totHeight += bt.getHeight();
}
return (double)totHeight / trees.size();
}
S 271