Trees - PowerPoint PPT Presentation

1 / 157
About This Presentation
Title:

Trees

Description:

You've probably seen family trees like the one at the right. 2. Building a Tree ... the ancestors (parents, grand parents and so on) of one person in a family tree ... – PowerPoint PPT presentation

Number of Views:100
Avg rating:3.0/5.0
Slides: 158
Provided by: lowel3
Category:
Tags: family | tree | trees

less

Transcript and Presenter's Notes

Title: Trees


1
Trees
  • A tree is a data structure similar to a linked
    list, except there is more than one pointer
  • You've probably seen family trees like the one at
    the right

2
Building a Tree
  • To model this in Java we would need a class like

class TreeNode String myName treeNode
pMom, pDad treeNode (String sN, treeNode pL,
treeNode pR) myName sN pMom pL pDad
pR
3
Building a Tree
  • Since we don't know who Ellen and John's parents
    are, we'll use null

TreeNode pEllen new TreeNode("Ellen
Rimbauer",null,null) TreeNode pJohn new
TreeNode("John Rimbauer",null,null)
4
Building a Tree
  • Adam's parents are Ellen and John

TreeNode pEllen new TreeNode("Ellen
Rimbauer",null,null) TreeNode pJohn new
TreeNode("John Rimbauer",null,null) TreeNode
pAdam new TreeNode("Adam
Rimbauer",pEllen,pJohn)
5
Building a Tree
  • April's parents are also Ellen and John
  • Steven's dad is Adam, but we don't know his
    mother

TreeNode pAdam new TreeNode("Adam
Rimbauer",pEllen,pJohn) TreeNode pApril
new TreeNode("April Rimbauer",pEllen,pJohn) TreeN
ode pSteven new TreeNode("Steven
Rimbauer",null, pAdam)
6
An better encapsulated tree class
  • public class TreeNode
  • private Object value //note Object
  • private TreeNode left
  • private TreeNode right
  • public TreeNode(Object initValue, TreeNode
  • initLeft, TreeNode initRight)
  • value initValue left initLeft
  • right initRight
  • public Object getValue() return value
  • public TreeNode getLeft() return left
  • public TreeNode getRight() return right
  • public void setValue(Object theNewValue)
  • value theNewValue
  • public void setLeft(TreeNode theNewLeft)
  • left theNewLeft
  • public void setRight(TreeNode theNewRight)
  • right theNewRight

7
Methods that operate on Trees
  • Just like a linked list, we can make a
    fill-in-the-blank outline for methods that
    operate on treeNodes
  • . . . funForTreeNode (TreeNode root)
  • if (root null)
  • . . . . .
  • else
  • . . . . .root.getValue(). . . .
  • . . . FunForTree(root.getLeft()) . . . .
  • . . . FunForTree(root.getRight()). . . .

8
Methods that operate on Trees
  • We have three possible arrangements for the
    recursive calls Pre-Order
  • . . . funForTreeNode (TreeNode root)
  • if (root null)
  • . . . . .
  • else
  • . . . . .root.getValue(). . . .
  • . . . . FunForTree(root.getLeft()). . . .
  • . . . . FunForTree(root.getRight()) . . .

9
Methods that operate on Trees
  • We have three possible arrangements for the
    recursive calls In-Order
  • . . . funForTreeNode (TreeNode root)
  • if (root null)
  • . . . . .
  • else
  • . . . . FunForTree(root.getLeft()). . . .
  • . . . . .rootgetValue(). . . .
  • . . . . FunForTree(root.getRight()) . . .

10
Methods that operate on Trees
  • We have three possible arrangements for the
    recursive calls Post-Order
  • . . . funForTreeNode (TreeNode root)
  • if (root null)
  • . . . . .
  • else
  • . . . . FunForTree(root.getLeft()). . . .
  • . . . . FunForTree(root.getRight()) . . .
  • . . . . .root.getValue(). . . .

11
Problem Write a method that counts all the
ancestors (parents, grand parents and so on) of
one person in a family tree
  • int CountParents (treeNode root)
  • if (root null)
  • . . . . .
  • else
  • . . . . .root.getValue(). . . .
  • . . . . CountParents(root.getLeft()). . .
  • . . . . CountParents(root.getRight()) .
    . .

12
Problem Write a method that counts all the
ancestors (parents, grand parents and so on) of
one person in a family tree
  • int CountParents (TreeNode root)
  • if (root null)
  • return 0
  • else
  • . . . . root.getValue()
  • . . . . CountParents(root.getLeft()) . .
    . .
  • . . . . CountParents(root.getRight()). .
    . .

13
Problem Write a method that counts all the
ancestors (parents, grand parents and so on) of
one person in a family tree
  • int CountParents (TreeNode root)
  • if (root null)
  • return 0
  • else
  • return 1
  • CountParents(root.getLeft())
  • CountParents(root.getRight())

14
Problem Write a method that counts all the
ancestors (parents, grand parents and so on) of
one person in a family tree
  • int CountParents (TreeNode root)
  • if (root null)
  • return 0
  • else
  • return 1
  • CountParents(root.getLeft())
  • CountParents(root.getRight())
  • The problem with this solution is that the person
    counts as their own ancestor

15
Problem Write a method that counts all the
ancestors (parents, grand parents and so on) of
one person in a family tree
  • We can write a helper method to fix this problem
  • int CountAncestors(TreeNode root)
  • return CountParents(root)-1
  • //or
  • int CountAncestors(TreeNode root)
  • return CountParents(root.pMom)
  • CountParents(root.pDad)

16
Binary Search Trees
  • Definition A BST is a tree where each node has
    two pointers and for any node, the element in the
    node is larger than all elements in this node's
    left subtree and smaller than all elements in
    this node's right subtree
  • Huh?

17
Binary Search Trees
  • Some of these are BSTs, some aren't

10
10
10
5
5
15
5
11
4
11
4
11
4
7
16
12
4
7
12
7
12
3
7
5
10
5
9
4
11
5
11
3
7
4
7
12
9
18
Binary Search Trees
  • These are BSTs

10
10
5
10
5
15
5
11
4
11
4
11
4
7
16
12
4
7
12
3
7
7
12
5
9
19
Binary Search Trees
  • These aren't BSTs

5
10
4
11
5
11
3
7
4
7
12
9
20
Building a BST
  • Let's say you want to build a BST from the
    numbers 2 1 8 7 3

21
Building a BST
  • Let's say you want to build a BST from the
    numbers 2 1 8 7 3

2
22
Building a BST
  • Let's say you want to build a BST from the
    numbers 2 1 8 7 3

2
1
23
Building a BST
  • Let's say you want to build a BST from the
    numbers 2 1 8 7 3

2
1
8
24
Building a BST
  • Let's say you want to build a BST from the
    numbers 2 1 8 7 3

2
1
8
7
25
Building a BST
  • Let's say you want to build a BST from the
    numbers 2 1 8 7 3

2
1
8
7
3
26
Tree Vocabulary
E
B
H
A
C
I
G
D
  • BST are usually displayed "upside down", the root
    is at the top
  • Each element is a node
  • Any node whose left and right subtrees are empty
    is a leaf
  • The level of a node counts down from the root A,
    C, G and I are all at level 2, the level of the
    tree is 3
  • The height of a tree is the number of nodes on
    the longest path from root to leaf

27
Tree Vocabulary
E
B
H
A
C
I
G
D
  • A balanced tree has approximately the same number
    of nodes in the left and right subtrees.
  • A full binary tree has every leaf on the same
    level, every nonleaf node is the parent of two
    children
  • A complete binary tree is either full or full
    through the next to last level with the leaves as
    far left as possible

28
Searching a BST
E
B
H
A
C
I
G
D
  • If a BST is reasonably balanced, finding a node
    is quick and easy.
  • Let's say we are looking for 'D'.
  • Start at the root. If the node you are looking
    for is smaller go left, otherwise, go right
  • Even though there are 8 nodes, the most nodes
    we'll visit is 4--the height of the tree

29
Searching a BST
  • If a linked list has 1000 nodes, and you are
    searching for a particular value, what is the
    most nodes you would have to visit?

30
Searching a BST
  • If a linked list has 1000 nodes, and you are
    searching for a particular value, what is the
    most nodes you would have to visit?
  • 1000

31
Searching a BST
  • If a linked list has 1000 nodes, and you are
    searching for a particular value, what is the
    most nodes you would have to visit?
  • 1000
  • If a balanced BST has 1000 nodes, and you are
    searching for particular value, what is the most
    nodes you will have to visit?

32
Searching a BST
  • If a linked list has 1000 nodes, and you are
    searching for a particular value, what is the
    most nodes you would have to visit?
  • 1000
  • If a balanced BST has 1000 nodes, and you are
    searching for particular value, what is the most
    nodes you will have to visit?
  • 10

33
Big O notation
  • If a linked list has n nodes, at most we would
    have to visit n nodes
  • O(n)
  • If a balanced BST has n nodes, at most we would
    have to visit log2 n nodes
  • O(log n)

34
Traversing a tree
  • Pre-Order
  • Visit
  • Left
  • Right
  • In-Order
  • Left
  • Visit
  • Right
  • Post-Order
  • Left
  • Right
  • Visit

E
B
H
A
C
I
G
D
35
Traversing a tree
  • Pre-Order
  • Visit
  • Left
  • Right

E
B
H
A
C
I
G
D
36
Traversing a tree
  • Pre-Order
  • Visit
  • Left
  • Right
  • E B A C D H G I

E
B
H
A
C
I
G
D
37
Traversing a tree
  • In-Order
  • Left
  • Visit
  • Right

E
B
H
A
C
I
G
D
38
Traversing a tree
  • In-Order
  • Left
  • Visit
  • Right
  • A B C D E G H I

E
B
H
A
C
I
G
D
39
Traversing a tree
  • Post-Order
  • Left
  • Right
  • Visit

E
B
H
A
C
I
G
D
40
Traversing a tree
  • Post-Order
  • Left
  • Right
  • Visit
  • A D C B G I H E

E
B
H
A
C
I
G
D
41
Practice Quiz Question What will the three
traversals give for this tree?
5
4
11
3
7
42
A BST class
  • Typically we build a BST from two classes
  • TreeNode represents a single node and BSTree
    represents the entire tree
  • class TreeNode
  • private Object value //note Object!
  • private TreeNode left
  • private TreeNode right
  • public TreeNode(Object initValue, TreeNode
  • initLeft, TreeNode initRight)
  • value initValue left initLeft
  • right initRight
  • public Object getValue() return value
  • public TreeNode getLeft() return left
  • public TreeNode getRight() return right
  • public void setValue(Object theNewValue)
  • value theNewValue
  • public void setLeft(TreeNode theNewLeft)
  • left theNewLeft
  • public void setRight(TreeNode theNewRight)

43
A BST class
  • The BSTree class has a variable for the root and
    methods to count, display, find and delete the
    nodes
  • Typically, for each operation is there a simple
    method that "starts" the process, and a recursive
    "helper" that does the work
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public int startCount()
  • private int count(TreeNode root)
  • //and lots more

44
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public int startCount()
  • return count(root)
  • private int count(TreeNode root)
  • //and lots more

45
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public int startCount()
  • return count(root)
  • private int count(TreeNode root)
  • if(root null)
  • . . .
  • else
  • . . .count(root.getLeft()). . .
  • . . .root.getValue(). . .
  • . . .count(root.getRight()). . .

46
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public int startCount()
  • return count(root)
  • private int count(TreeNode root)
  • if(root null)
  • return 0
  • else
  • . . .count(root.getLeft()). . .
  • . . .root.getValue(). . .
  • . . .count(root.getRight()). . .

47
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public int startCount()
  • return count(root)
  • private int count(TreeNode root)
  • if(root null)
  • return 0
  • else
  • return count(root.getLeft())
  • 1
  • count(root.getRight())

48
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public boolean startFind(Comparable data)
  • return find(root, data)
  • public boolean find(TreeNode root,
  • Comparable data)

49
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public boolean startFind(Comparable data)
  • return find(root, data)
  • public boolean find(TreeNode root,
  • Comparable data)
  • if(root null)
  • . . .
  • else
  • . . .find(root.getLeft(),data). . .
  • . . .root.getValue(). . .
  • . . .find(root.getRight(),data). . .

50
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public boolean startFind(Comparable data)
  • return find(root, data)
  • public boolean find(TreeNode root,
  • Comparable data)
  • if(root null)
  • return false
  • else
  • . . .find(root.getLeft(),data). . .
  • . . .root.getValue(). . .
  • . . .find(root.getRight(),data). . .

51
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public boolean startFind(Comparable data)
  • return find(root, data)
  • public boolean find(TreeNode root,
  • Comparable data)
  • if(root null)
  • return false
  • else
  • return find(root.getLeft(),data)
  • data.compareTo(root.getValue()) 0
  • find(root.getRight(),data)

52
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public boolean startFind(Comparable data)
  • return find(root, data)
  • public boolean find(TreeNode root,
  • Comparable data)
  • if(root null)
  • return false
  • else
  • if(data.compareTo(root.getValue())
  • return find(root.getLeft(),data)
  • . . .root.getValue(). . .

53
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public boolean startFind(Comparable data)
  • return find(root, data)
  • public boolean find(TreeNode root,
  • Comparable data)
  • if(root null)
  • return false
  • else
  • if(data.compareTo(root.getValue())
  • return find(root.getLeft(),data)
  • if(data.compareTo(root.getValue() 0)

54
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public boolean startFind(Comparable data)
  • return find(root, data)
  • public boolean find(TreeNode root,
  • Comparable data)
  • if(root null)
  • return false
  • else
  • if(data.compareTo(root.getValue())
  • return find(root.getLeft(),data)
  • if(data.compareTo(root.getValue() 0)

55
A BST class
  • class BSTree
  • private TreeNode root
  • public BSTree()
  • public boolean startFind(Comparable data)
  • return find(root, data)
  • public boolean find(TreeNode root,
  • Comparable data)
  • if(root null)
  • return false
  • else
  • if(data.compareTo(root.getValue())
  • return find(root.getLeft(),data)
  • else if(data.compareTo(

56
Problem add a trim method to the BSTree class.
trim removes all leaves in the tree
Before
After
56
56
-2
78
-2
4
4
6
1
6
16
16
7
57
Problem add a trim method to the BSTree class.
trim removes all leaves in the tree
  • public void startTrim()
  • trim(root)
  • private void trim(TreeNode root)
  • if(root null)
  • . . . .
  • else
  • . . . root.getValue(). . .
  • . . .trim(root.getLeft()). . .
  • . . .trim(root.getRight()) . . .

58
Problem add a trim method to the BSTree class.
trim removes all leaves in the tree
  • public void startTrim()
  • trim(root)
  • private void trim(TreeNode root)
  • if(root null)
  • return
  • else
  • . . . root.getValue(). . .
  • . . .trim(root.getLeft()). . .
  • . . .trim(root.getRight()) . . .

59
Problem add a trim method to the BSTree class.
trim removes all leaves in the tree
  • public void startTrim()
  • trim(root)
  • private void trim(TreeNode root)
  • if(root null)
  • return
  • else
  • //if left is leaf delete it
  • //if right is leaf delete it
  • trim(root.getLeft())
  • trim(root.getRight())

60
Problem add a trim method to the BSTree class.
trim removes all leaves in the tree
  • public void startTrim()
  • trim(root)
  • private void trim(TreeNode root)
  • if(root null)
  • return
  • else
  • //if left is leaf delete it
  • if(root.getLeft()!null
  • root.getLeft().getRight()null
  • root.getLeft().getLeft()null)
  • root.setLeft(null)
  • //if right is leaf delete it
  • trim(root.getLeft())
  • trim(root.getRight())

61
Problem add a trim method to the BSTree class.
trim removes all leaves in the tree
  • public void startTrim()
  • trim(root)
  • private void trim(TreeNode root)
  • if(root null)
  • return
  • else
  • //if left is leaf delete it
  • if(root.getLeft()!null
  • root.getLeft().getRight()null
  • root.getLeft().getLeft()null)
  • root.setLeft(null)
  • //if right is leaf delete it
  • if(root.getRight()!null
  • root.getRight().getRight()null

62
Problem add a trim method to the BSTree class.
trim removes all leaves in the tree
  • public void startTrim()
  • trim(root)
  • private void trim(TreeNode root)
  • if(root null)
  • return
  • else
  • //THIS DOESN'T WORK!!!
  • if(root.getLeft()null
  • root.getRight()null)
  • root null
  • trim(root.getLeft())
  • trim(root.getRight())

63
Deleting a node from a tree
  • Two steps
  • Locate Node to delete
  • Eliminate the Node
  • After locating the node, there are four
    possibilities
  • If it is a leaf, make the parent node point to
    null.
  • If it has one child on the right, make the parent
    node point to the right child
  • If it has one child on the left, make the parent
    node point to the left child.
  • If it has two children, the problem becomes much
    harder to solve.

64
Deleting a node from a tree
  • Three methods
  • public void startDelete(Comparable target)
  • private TreeNode delete(TreeNode node, Comparable
    target)
  • private TreeNode deleteTargetNode(TreeNode
    target)
  • startDelete() calls delete()
  • delete() recursively finds the node and calls
    deleteTargetNode()
  • deleteTargetNode() eliminates the node
  • code is in ICT Java curriculum lesson 36

65
What does this have to do with computer
programming?
66
Stacks
  • Think of a stack of plates at a buffet
  • The first plate that is placed on the stack is
    the last plate to be taken off
  • A stack is called a LIFO, last in first out
    structure (or sometimes FILO)
  • Placing something on the stack is called pushing
  • Taking it off is popping

67
Stacks
  • A PEZ dispenser is another example of a stack

68
The Stack interface
  • public interface Stack
  • boolean isEmpty()
  • void push(Object x)
  • Object pop()
  • Object peekTop()
  • To Use the ArrayStack class that implements this
    interface, you will need to download ap.jar

69
What is the output?
  • import ap.
  • public class StackDemo
  • public static void main(String args)
  • Stack s new ArrayStack()
  • s.push(new Integer(5))
  • s.push(new Integer(3))
  • s.push(new Integer(2))
  • s.pop()
  • System.out.println(s.peekTop())
  • s.pop()
  • int nNum ((Integer)s.pop()).intValue()
  • System.out.println(nNum)

70
Problem write a program that uses a stack to
reverse a string
  • String sForward
  • "A Man! A Plan! A Canal! Panama!"
  • String sBackward new String("")
  • Stack s new ArrayStack()
  • for(int nI 0 nI
  • s.push(new Character(sForward.charAt(nI)))
  • while(!s.isEmpty())
  • sBackward s.pop()
  • System.out.println(sBackward)
  • //Displays !amanaP !lanaC A !nalP A !naM A

71
What is the output?
  • Stack s new ArrayStack()
  • int nX 2, nY 3
  • s.push(new Integer(nX))
  • s.push(new Integer(2nY))
  • s.push(new Integer(4))
  • nY ((Integer)s.pop()).intValue()
  • s.push(new Integer(7))
  • s.pop()
  • nX ((Integer)s.peekTop()).intValue()
  • while(!s.isEmpty())
  • System.out.println(s.pop())
  • System.out.println("nX is " nX)

72
The Queue interface
  • Think of the line of people at a buffet
  • The first person in line is the first person to
    get their food
  • A queue is called a FIFO, first in first out
    structure
  • To place something at the end of the queue is
    called enqueue
  • Removing the element at the front of the queue is
    called dequeue

73
The Queue interface
  • public interface Queue
  • boolean isEmpty()
  • void enqueue(Object x)
  • Object dequeue()
  • Object peekFront()

74
The Queue interface
  • import ap.
  • public class QueueDemo
  • public static void main(String args)
  • Queue q new ListQueue()
  • q.enqueue(new Integer(5))
  • q.enqueue(new Integer(3))
  • q.enqueue(new Integer(2))
  • q.dequeue()
  • System.out.println(q.dequeue())

75
What is the output of this program?
  • Queue q new ListQueue()
  • int nX 2, nY 3
  • q.enqueue(new Integer(nX))
  • q.enqueue(new Integer(2nY))
  • q.enqueue(new Integer(4))
  • nY ((Integer)q.dequeue()).intValue()
  • q.enqueue(new Integer(7))
  • q.dequeue()
  • nX ((Integer)q.peekFront()).intValue()
  • while(!q.isEmpty())
  • System.out.println(q.dequeue())
  • System.out.println("nX is " nX)

76
A Hospital Emergency Room
  • You've seen how stacks and queues model the way a
    buffet works
  • People come to a hospital for treatment Should
    they be stored in a queue (FIFO), or a stack
    (LIFO), or something else? How do you determine
    who gets treated first?

77
Priority Queues
  • A Priority Queue is a data structure (like a
    linked list, stack, tree, queue, array, etc) for
    storing a collection of items
  • Each node has data and a priority
  • A Priority Queue is NOT A QUEUE, but a complete
    binary tree
  • Priority Queues are also called "Heaps"

78
heaps (priority queues)
  • There are two versions
  • min heaps (the value of every node is less than
    or equal to the value in each of its children)
  • max heaps (the value is each of its children)
  • The AP exam uses a min heap
  • If you used a heap to store the names of patients
    awaiting treatment, the person on the top of the
    heap would be the person most in need

1
6
4
8
7
9
5
12
20
79
Priority Queues
  • One way to construct a priority queue is to store
    each node in an array
  • The root is at index one (index zero is unused)
  • If a node at index k has children, the left child
    is at 2 k and the right child is at 2 k 1
  • For example, the node with value 4 is at index 3
  • It's left child is at index 6 (23)
  • It's right child is at index 7 (231)

1
6
4
8
7
9
5
12
20
0 1 2 3 4 5 6 7 8 9
1 6 4 8 7 9 5 12 20
80
Priority Queues
  • A well designed heap allows
  • Rapid insertion of elements that arrive in
    arbitrary order
  • Rapid retrieval of the item with the highest
    priority
  • Insertion and deletion of elements in a heap are
    O(log n)

81
Fixing the heap (from the bottom)
  • If we add or remove and element, we will have to
    rearrange the nodes to keep it a heap (called
    reheaping)
  • For example, let's add a new node with the value
    2 to the heap

1
6
4
8
7
9
5
12
20
82
Fixing the heap (from the bottom)
  • The heap is no longer a min heap
  • It needs to be reheaped from the bottom up

1
6
4
8
7
9
5
12
20
2
83
Fixing the heap (from the bottom)
  • We'll start at the last node with children (which
    is the number of nodes divided by 2)
  • We'll compare each node with it's children
  • If an element has a lower priority than one of
    its children, we swap it with the child with the
    highest priority

1
6
4
8
7
9
5
12
20
2
84
Fixing the heap (from the bottom)
  • We'll start at the last node with children (which
    is the number of nodes divided by 2)
  • We'll compare each node with it's children
  • If an element has a lower priority than one of
    its children, we swap it with the child with the
    highest priority

1
6
4
8
2
9
5
12
20
7
85
Fixing the heap (from the bottom)
  • We'll start at the last node with children (which
    is the number of nodes divided by 2)
  • We'll compare each node with it's children
  • If an element has a lower priority than one of
    its children, we swap it with the child with the
    highest priority

1
2
4
8
6
9
5
12
20
7
86
Fixing the heap (from the top)
  • If we remove an element, we'll move each element
    down one position in the array

1
2
4
8
6
9
5
12
20
7
0 1 2 3 4 5 6 7 8 9 10
1 2 4 8 6 9 5 12 20 7
87
Fixing the heap (from the top)
  • If we remove an element, we'll move each element
    down one position in the array

2
4
8
6
9
5
12
20
7
0 1 2 3 4 5 6 7 8 9 10
2 4 8 6 9 5 12 20 7
88
Fixing the heap (from the top)
  • Then we'll have to reheap from the top down

2
4
8
6
9
5
12
20
7
89
Fixing the heap (from the top)
  • Now it's fixed
  • reheaping is O(log n)
  • Insertion or deletion is O(1), but then you have
    to reheap
  • A Heap can be used to sort it's called Heap Sort

2
4
5
6
9
8
12
20
7
90
The PriorityQueue interface
  • public interface PriorityQueue
  • boolean isEmpty()
  • void add(Object x)
  • Object removeMin()
  • Object peekMin()

91
What is the output?
  • import ap.
  • public class PriorityQueueDemo
  • public static void main(String args)
  • PriorityQueue pq
  • new ArrayPriorityQueue()
  • pq.add(new Integer(5))
  • pq.add(new Integer(2))
  • pq.add(new Integer(3))
  • while(!pq.isEmpty())
  • System.out.println(pq.removeMin())

92
Collections
  • A collection is any bunch of objects you can
    think of
  • For the AP AB exam, you are expected to know
  • Three interfaces Set, List and Map
  • Six classes
  • ArrayList, LinkedList, (implement List)
  • HashSet (implements Set)
  • TreeSet(implements SortedSet)
  • HashMap (implements Map)
  • TreeMap (implements SortedMap)

93
Collections and Iterators
  • An Iterator is like a loop
  • It allows you to go through the entire collection
    in proper sequence
  • The three methods of the Iterator interface are
    next, hasNext and remove

94
ArrayList vs. LinkedList
  • The code to use both is nearly identical
  • The difference is in the implementation
    ArrayList uses an array, LinkedList is a linked
    list
  • For large amounts of data, there may be
    differences in performance
  • Most of the time, though, it really doesn't make
    much difference which you use

95
ArrayList vs. LinkedList
  • Adding or deleting the front is O(n) for
    ArrayList, O(1) for LinkedList
  • Accessing or changing the middle is O(1) for
    ArrayList, O(n) for LinkedList
  • Inserting or deleting in the middle is O(n) for
    both
  • In "real life", because the code is generic, it's
    easy to test which is faster for a particular set
    of data

96
Using an Iterator
  • import java.util.
  • import java.util.List
  • public class IteratorDemo
  • public static void main(String args)
  • List L new ArrayList()
  • L.add(new Integer(15))
  • L.add(new Integer(2))
  • L.add(new Integer(37))
  • Iterator itr L.iterator()
  • while(itr.hasNext())
  • System.out.println(itr.next())

97
Using an Iterator
  • import java.util.
  • import java.util.List
  • public class IteratorDemo
  • public static void main(String args)
  • List L new ArrayList()
  • L.add(new Integer(15))
  • L.add(new Integer(2))
  • L.add(new Integer(37))
  • for(Iterator itr L.iterator()
  • itr.hasNext())
  • System.out.println(itr.next())

98
The syntax for LinkedList is identical to
ArrayList
  • import java.util.
  • import java.util.List
  • public class IteratorDemo
  • public static void main(String args)
  • List L new LinkedList()
  • L.add(new Integer(15))
  • L.add(new Integer(2))
  • L.add(new Integer(37))
  • for(Iterator itr L.iterator()
  • itr.hasNext())
  • System.out.println(itr.next())

99
What is the output?
  • List L new LinkedList()
  • L.add(new Integer(15))
  • L.add(new Integer(2))
  • L.add(new Integer(37))
  • Iterator itr L.iterator()
  • while(itr.hasNext())
  • System.out.println(itr.next())
  • itr L.iterator()
  • while(itr.hasNext())
  • if(((Integer)itr.next()).intValue()5 0)
  • itr.remove()
  • itr L.iterator()
  • while(itr.hasNext())
  • System.out.println(itr.next())

100
Iterator vs. ListIterator
  • A ListIterator is exactly like an Iterator but
    with two additional methods
  • void add(Object o) (adds to list before next
    element)
  • void set(Object o) (replaces the last element
    returned by next)

101
What is the output?
  • List l new LinkedList()
  • l.add(new String("Alices"))
  • l.add(new String("Adventures"))
  • l.add(new String("In"))
  • l.add(new String("Wonderland"))
  • ListIterator i l.listIterator()
  • while(i.hasNext())
  • String temp (String)i.next()
  • if(temp.length()2)
  • i.set(temp.toUpperCase())
  • i l.listIterator()
  • while(i.hasNext())
  • System.out.println(i.next())

102
What is the output?
  • List L new LinkedList()
  • L.add(new Integer(15))
  • L.add(new Integer(2))
  • L.add(new Integer(37))
  • ListIterator itr L.listIterator()
  • while(itr.hasNext())
  • if(((Integer)itr.next()).intValue()5 0)
  • itr.add(new Integer(3))
  • else
  • itr.set(new Integer(7))
  • Iterator itr2 L.iterator()
  • while(itr2.hasNext())
  • System.out.println(itr2.next())

103
hash tables
  • A hash table is an improvement of a bucket sort
  • less wasted space
  • can store 2 or more items in the same "bucket"
  • A hash table can be thought of as an array of
    linked lists

104
hash tables
  • Let's say I have five numbers, each of which is
    between 0 and 400
  • 7 266 399 12 125
  • I don't want to make 400 "buckets", because 395
    of them will be empty!
  • I'll take the number 5 and use that to decide
    where to store it
  • I'm using 5 because there are 5 numbers to be
    sortedto 5 buckets
  • In this example, 5 is the "hash function"

105
hash tables
7
0
266
1
399
2
12
3
125
4
106
hash tables
7 5 2
0
266
1
399
2
12
3
125
4
107
hash tables
0
266 5 1
1
399
2
7
12
3
125
4
108
hash tables
0
1
266
399 5 4
2
7
12
3
125
4
109
hash tables
0
1
266
2
7
12 5 2
3
125
4
399
110
hash tables
12 and 7 are placed in the location by the hash
function. This is called a collision. 12 is
inserted at the head of the linked list.
0
1
266
2
7
12
3
125
4
399
111
hash tables
0
1
266
2
7
12
3
125 5 0
4
399
112
hash tables
0
In this example, one of the five spots is
empty. of null pointers 20 The average
length of the (non-empty) linked lists are (1
1 2 1)/4 1.25 Ideally, we'd like to have 0
null pointers and an average length of 1. We
could write a different hash function and see if
it makes an improvement
125
1
266
2
7
12
3
4
399
113
hash function add the digits up and then 5
7 7 5 2
0
266 14 5 4
1
399
399 21 5 1
2
7
12 3 5 3
3
12
125
125 8 5 3
4
266
114
hash function sin(number) 2.5 2.5
sin(7)2.52.52
0
266
sin(266)2.52.50
1
sin(399)2.52.54
2
7
sin(12)2.52.53
3
12
sin(125)2.52.54
4
399
125
115
hash function .number 6
.764
0
125
12
.26661
1
266
.39962
2
399
.1260
3
.12560
4
7
116
hash tables
  • If there are no collisions, putting data in a
    Hash table is O(1)
  • If there are no collisions, searching for a
    number is O(1)
  • Just use the "hash function" to find where the
    number would be stored

117
searching hash tables
0
Let's say I'm searching for the value 532. I do
5325 2. That means that 532 would be at
position 2 if it is in the hash table. We go to
the the linked list in position 2 and do a linear
search for the value 532.
125
1
266
2
7
12
3
4
399
118
hashCode()
  • You don't have to think of your own hashing
    method
  • Every class inherits hashCode() from Object
  • Uses "Some Formula" we don't know or care about
  • Every Object is associated with an integeer value
    called its hash code
  • equal objects have equal hash codes

119
The Set interface
  • No duplicate elements
  • Like a "mathematical" set
  • Implemented by HashSet and TreeSet
  • public interface Set
  • boolean add((Object obj)
  • boolean contains(Object obj)
  • boolean remove(Object obj)
  • int size()
  • Iterator iterator()

120
Using a HashSet to store a collection of people
  • import java.util.
  • public class HashSetDemo
  • public static void main(String args)
  • Set s new HashSet()
  • s.add("Mary")
  • s.add("Joan")
  • s.add("Mary") //note duplicate
  • s.add("Dennis")
  • System.out.println(s.size())
  • Iterator itr s.iterator()
  • while(itr.hasNext())
  • System.out.println(itr.next())
  • / Sample Output
  • 3

121
Using a TreeSet to store a collection of people
  • import java.util.
  • public class TreeSetDemo
  • public static void main(String args)
  • Set s new TreeSet()
  • s.add("Mary")
  • s.add("Joan")
  • s.add("Mary") //note duplicate
  • s.add("Dennis")
  • System.out.println(s.size())
  • Iterator itr s.iterator()
  • while(itr.hasNext())
  • System.out.println(itr.next())
  • / Sample Outputnote different order of output
  • 3

122
Comparing sets
  • import java.util.
  • public class SetDemo
  • public static void main(String args)
  • Set s new TreeSet()
  • s.add("Mary")
  • s.add("Joan")
  • s.add("Mary") //note duplicate
  • s.add("Dennis")
  • Set t new HashSet()
  • t.add("Mary")
  • t.add("Joan")
  • t.add("Dennis")
  • System.out.println(s.equals(t))

123
TreeSet vs. HashSet
  • HashSet is faster, but unordered
  • HashSet is O(1) for add, remove and contains
  • Iterating through a HashSet gives items in no
    particular order
  • TreeSet is slower, but sorted
  • TreeSet is O(log n) for add, remove and contains
  • TreeSet is a balanced Binary Search Tree
  • TreeSet uses compareTo, so any items in the set
    need to be "mutually comparable"
  • TreeSet is sorted in ascending order
  • Iterating through TreeSet gives all items in
    ascending order

124
The Map interface
  • Implemented by HashMap and TreeMap
  • Each item must have unique "key"
  • No iterator! (e.g. you won't be expected to
    display all items)
  • public interface Map
  • Object put(Object key, Object value)
  • Object get(Object key)
  • Object remove(Object key)
  • boolean containsKey(Object key)
  • int size()
  • Set keySet()

125
Using a HashMap to store a collection of people
using SS key
  • import java.util.
  • public class HashDemo
  • public static void main(String args)
  • Map h new HashMap()
  • h.put("123456789", "Joe Smith")
  • h.put("456719812", "Joe Smith")
  • h.put("731851382", "Homer Simpson")
  • h.put("725248225", "Joe Montana")
  • h.put("005049825", "Lisa Carlisle")
  • System.out.println(h.get("456719812"))
  • System.out.println(h.get("725248225"))

126
Using a TreeMap is identical
  • import java.util.
  • public class HashDemo
  • public static void main(String args)
  • Map h new TreeMap()
  • h.put("123456789", "Joe Smith")
  • h.put("456719812", "Joe Smith")
  • h.put("731851382", "Homer Simpson")
  • h.put("725248225", "Joe Montana")
  • h.put("005049825", "Lisa Carlisle")
  • System.out.println(h.get("456719812"))
  • System.out.println(h.get("725248225"))

127
Sets vs. Maps
  • Map has a get() method, Set doesn't
  • Maps can have duplicate items, as long as they
    have different keys
  • Set has an iterator, Map doesn't
  • If you want to be able to retrieve a single item,
    use a Map
  • If you will only deal with the items as a group,
    use a Set

128
AP exam format
  • Both A and AB are two sections
  • 40 multiple choice questions 115
  • 4 free response questions 145
  • Usually, you are asked write a function for the
    free response questions given a header and a task
  • One free response question will be about the MBCS
    (the same question is usually on both exams)
  • 5 or 6 multiple choice questions will be about
    the MBCS
  • You will be given a "quick reference guide" to
    the AP C classes and MBCS code

129
AP exam grading
  • Here are the statistics for the 1999 exam
  • Grade A exam AB exam
  • 5 75 70
  • 4 56 60
  • 3 41 41
  • 2 30 31
  • 1 0 0

130
Ap exam tips
  • A exam one
  • "Distributing" the !
  • !(true false)
  • //is the same as
  • !true !false
  • //is the same as
  • false true
  • //is the same as
  • false

131
The worst mistake
  • Never display what you should return!
  • Problem Write a method that returns the sum of
    two numbers
  • double Sum(double dOne, double dTwo)
  • System.out.println(dOne dTwo)
  • NO NO NO NO!

132
The worst mistake
  • Never display anything unless you are asked!
  • Problem Write a method that returns the sum of
    two numbers
  • double Sum(double dOne, double dTwo)
  • System.out.println(dOne dTwo)
  • return dOne dTwo
  • NO NO NO NO!

133
The worst mistake
  • Now it's correct!
  • Problem Write a method that returns the sum of
    two numbers
  • double Sum(double dOne, double dTwo)
  • return dOne dTwo
  • Beginning programmers typically want to display
    everything. If they can't see it, they don't
    believe it exists. Don't let the grader think
    you're a rookie!

134
Design questions
  • Asks you to design a class
  • Problem Write a PopulationZone which should have
    methods that
  • retrieve zone's name
  • retrive zone's growth rate
  • set a new growth rate
  • retrieve population
  • retrieve population below a given age
  • adjust age distributions up one year

135
Ap exam tips
  • class PopulationZone
  • public
  • private

136
Ap exam tips
  • class PopulationZone
  • public
  • PopulationZone()
  • private

137
Ap exam tips
  • class PopulationZone
  • public
  • PopulationZone()
  • apstring GetZoneName()
  • private
  • apstring myName

138
Ap exam tips
  • class PopulationZone
  • public
  • PopulationZone()
  • apstring GetZoneName()
  • double GetGrowthRate()
  • private
  • apstring myName
  • double myRate

139
Ap exam tips
  • class PopulationZone
  • public
  • PopulationZone()
  • apstring GetZoneName()
  • double GetGrowthRate()
  • void SetGrowthRate(double dRate)
  • private
  • apstring myName
  • double myRate

140
Ap exam tips
  • class PopulationZone
  • public
  • PopulationZone()
  • apstring GetZoneName()
  • double GetGrowthRate()
  • void SetGrowthRate(double dRate)
  • int GetTotalPopulation()
  • int GetTotalPopulation(int nLimit)
  • private
  • apstring myName
  • double myRate
  • apvector naAges

141
Ap exam tips
  • class PopulationZone
  • public
  • PopulationZone()
  • apstring GetZoneName()
  • double GetGrowthRate()
  • void SetGrowthRate(double dRate)
  • int GetTotalPopulation()
  • int GetTotalPopulation(int nLimit)
  • void AgeOneYear()
  • private
  • apstring myName
  • double myRate
  • apvector naAges

142
Ap exam tips
  • class PopulationZone
  • public
  • PopulationZone()
  • apstring GetZoneName() const
  • double GetGrowthRate() const
  • void SetGrowthRate(double dRate)
  • int GetTotalPopulation() const
  • int GetTotalPopulation(int nLimit)
  • const
  • void AgeOneYear()
  • private
  • apstring myName
  • double myRate
  • apvector naAges

143
Ap exam tips
  • class PopulationZone
  • public
  • PopulationZone()
  • PopulationZone(apstring sName,
  • apvector naAges)
  • PopulationZone(apstring sName,
  • apvector naAges, double dRate)
  • apstring GetZoneName() const
  • double GetGrowthRate() const
  • void SetGrowthRate(double dRate)
  • int GetTotalPopulation() const
  • int GetTotalPopulation(int nLimit) const
  • void AgeOneYear()
  • private
  • apstring myName
  • double myRate
  • apvector naAges

144
Ap exam tips
  • class PopulationZone
  • public
  • PopulationZone()
  • PopulationZone(const apstring sName,
  • const apvector naAges)
  • PopulationZone(const apstring sName,
  • const apvector naAges, double dRate)
  • apstring GetZoneName() const
  • double GetGrowthRate() const
  • void SetGrowthRate(double dRate)
  • int GetTotalPopulation() const
  • int GetTotalPopulation(int nLimit) const
  • void AgeOneYear()
  • private
  • apstring myName
  • double myRate
  • apvector naAges

145
Ap exam tips
  • b.
  • double DemographicsTeenRatio(const
    PopulationZone z)const
  • return double(z.GetTotalPopulation(20)
  • z.GetTotalPopulation(13))/
  • z.GetTotalPopulation()

146
Ap exam tips
  • c.
  • apstring DemographicsFindMostTeens() const
  • int nMaxIndex 0
  • double dMaxRatio TeenRatio(countries0)
  • for(int nI1nI
  • if(TeenRatio(countriesnI) dMaxRatio)
  • dMaxRatio dRatio
  • nMaxIndex nI
  • return countriesnMaxIndex.GetName()

147
Answer to A exam practice
  • a.
  • int FindZero(const apvector A, int pos)
  • for(int nI pos nI
  • if(AnI 0)
  • return nI
  • return 1
  • b.
  • void SetZeros (apvector A)
  • int nFirst, nSecond
  • nFirst FindZero(A, 0)
  • nSecond FindZero(A,nFirst1)
  • for(int nI nFirst nI
  • AnI 0

148
Ap exam tips
  • class Type
  • public
  • Type()myNum 3
  • int GetNum()return myNum
  • void SetNum(int nNum)myNum nNum
  • void OneBigger()
  • private
  • int myNum

149
Ap exam tips
  • class Type
  • public
  • Type()myNum 3
  • int GetNum()return myNum
  • void SetNum(int nNum)myNum nNum
  • void OneBigger()
  • private
  • int myNum
  • void TypeOneBigger()
  • myNum //OK

150
Ap exam tips
  • class Type
  • public
  • Type()myNum 3
  • int GetNum()return myNum
  • void SetNum(int nNum)myNum nNum
  • void OneBigger()
  • private
  • int myNum
  • void TypeOneBigger()
  • myNum //OK
  • SetNum(GetNum() 1) //OK

151
Ap exam tips
  • class Type
  • public
  • Type()myNum 3
  • int GetNum()return myNum
  • void SetNum(int nNum)myNum nNum
  • void OneBigger()
  • private
  • int myNum
  • void TypeOneBigger()
  • myNum //OK
  • SetNum(GetNum() 1) //OK
  • int main()
  • Type aType
  • aType.OneBigger() //OK

152
Answer to A4 2001 (AB1 2001)
  • a.
  • bool WindowIsInBounds(int row, int col)
  • return (row 0) (row
  • (col 0) (col
  • b.
  • void WindowColorSquare(int Ulrow, int Ulcol,
    int N, int val)
  • for(int nRow Ulrow nRow
  • for(int nCol Ulcol nCol
  • if(IsInBounds(nRow,nCol))
  • myMatnRownColval

153
Answer to A4 2001 (AB1 2001)
  • c.
  • void Enlarge(Window W, const Rectagle rect,
  • int factor)
  • for(int nRow rect.numRows - 1 nRow 0
    nRow--)
  • for(int nCol rect.numCols - 1 nCol 0
    nCol--)
  • int nFromRow rect.ULrow nRow
  • int nFromCol rect.ULcol nCol
  • int nToRow rect.ULrow factor nRow
  • int nToCol rect.ULcol factor nCol
  • if (W.IsInBounds(nFromRow, nFromCol))
  • W.ColorSquare(nToRow, nToCol, factor,
  • W.ValAt(nFromRow,
    nFromCol))

154
Answer to A4 2001 (AB1 2001)
  • c.
  • void Enlarge(Window W, const Rectagle rect,
  • int factor)
  • Rectangle copy
  • for(int nRow rect.numRows() - 1 nRow 0
    nRow--)
  • for(int nCol rect.numCols() - 1 nCol 0
    nCol--)
  • int nFromRow rect.ULrow nRow
  • int nFromCol rect.ULcol nCol
  • int nToRow rect.ULrow factor nRow
  • int nToCol rect.ULcol factor nCol
  • if (W.IsInBounds(nFromRow, nFromCol))
  • W.ColorSquare(nToRow, nToCol, factor,
  • W.ValAt(nFromRow,
    nFromCol))

155
Answer to A4 1999 (AB1 1999)
  • a.
  • QuiltQuilt(istream inFile, int rowsOfBlocks,
    int colsOfBlocks)
  • myBlock(0,0),myRowsOfBlocks(rowsOfBlocks),
  • myColsOfBlocks(colsOfBlocks)
  • int nRows, nCols
  • inFilenRowsnCols // ½ pt
  • myBlock.resize(nRows,nCols) // ½ pt
  • for(int nRow0nRow
  • for(int nCol0nCol
  • inFilemyBlocknRownCol //1 pt
  • -1 for inFilemyRowsOfBlocksmyColsOfBlocks
  • -½ for nRows
Write a Comment
User Comments (0)
About PowerShow.com