Trees - PowerPoint PPT Presentation

1 / 126
About This Presentation
Title:

Trees

Description:

4. Adam's parents are Ellen and John. TreeNode ellen = new TreeNode('Ellen Rimbauer',null,null) ... Steven's dad is Adam, but we don't know his mother. TreeNode adam ... – PowerPoint PPT presentation

Number of Views:28
Avg rating:3.0/5.0
Slides: 127
Provided by: lowel3
Category:
Tags: adam | 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 ellen new TreeNode("Ellen
Rimbauer",null,null) TreeNode john new
TreeNode("John Rimbauer",null,null)
4
Building a Tree
  • Adam's parents are Ellen and John

TreeNode ellen new TreeNode("Ellen
Rimbauer",null,null) TreeNode john new
TreeNode("John Rimbauer",null,null) TreeNode
adam new TreeNode("Adam
Rimbauer",ellen,john)
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 adam new TreeNode("Adam
Rimbauer",ellen,john) TreeNode april new
TreeNode("April Rimbauer",ellen,john) TreeNode
steven new TreeNode("Steven
Rimbauer",null, adam)
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
  • . . . someTreeNodeMethod (TreeNode root)
  • if (root null)
  • . . . . .
  • else
  • . . . . .root.getValue(). . . .
  • . . someTreeNodeMethod (root.getLeft()) .
    .
  • . . someTreeNodeMethod (root.getRight()).
    .

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

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

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

11
Problem Write a method that displays all the
people in a family tree
  • void display (treeNode root)
  • if (root null)
  • . . . . .
  • else
  • . . . . .root.getValue(). . . .
  • . . . . display(root.getLeft()). . .
  • . . . . display(root.getRight()) . . .

12
Problem Write a method that displays all the
people in a family tree
  • void display (treeNode root)
  • if (root null)
  • //do nothing
  • else
  • System.out.println(root.getValue())
  • display(root.getLeft())
  • dipslay(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)
  • . . . . .
  • else
  • . . . . .root.getValue(). . . .
  • . . . . 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
  • . . . . root.getValue()
  • . . . . CountParents(root.getLeft()) . .
    . .
  • . . . . CountParents(root.getRight()). .
    . .

15
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())

16
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

17
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)

18
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?

19
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
20
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
21
Binary Search Trees
  • These aren't BSTs

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

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

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

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

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

2
1
8
7
27
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
28
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

29
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

30
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

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?

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

33
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?

34
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

35
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)

36
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
37
Traversing a tree
  • Pre-Order
  • Visit
  • Left
  • Right

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

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

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

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

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

E
B
H
A
C
I
G
D
43
Practice Quiz Question What will the three
traversals give for this tree?
5
4
11
3
7
44
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)

45
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

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

47
Problem Write a count method that returns the
count of the nodes in the tree
48
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()). . .

49
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()). . .

50
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())

51
Problem Write a find method that returns true if
a given value is in the tree, and false otherwise
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)

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)
  • . . .
  • else
  • . . .find(root.getLeft(),data). . .
  • . . .root.getValue(). . .
  • . . .find(root.getRight(),data). . .

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
  • . . .find(root.getLeft(),data). . .
  • . . .root.getValue(). . .
  • . . .find(root.getRight(),data). . .

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
  • return find(root.getLeft(),data)
  • data.compareTo(root.getValue()) 0
  • find(root.getRight(),data)

56
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()) lt 0)
  • return find(root.getLeft(),data)
  • . . .root.getValue(). . .

57
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()) lt 0)
  • return find(root.getLeft(),data)
  • if(data.compareTo(root.getValue() 0)

58
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()) lt 0)
  • return find(root.getLeft(),data)
  • if(data.compareTo(root.getValue() 0)

59
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()) lt 0)
  • return find(root.getLeft(),data)
  • else if(data.compareTo(

60
Practice Quiz Question 1 draw the tree2 copy
the following code into an Applet named
BSTreeQuiz and complete the display and
displayHelper methods
  • import java.awt.
  • import java.applet.
  • public class BSTreeQuiz extends Applet
  • public void init()
  • BSTree theTree new BSTree()
  • theTree.display()
  • 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

61
Binary Expression TreesAn inorder traversal
gives a mathematical expression


9
/
-5
3
2
3
5 3
9 (2/3)
62
Binary Expression TreesEvaluate this expression
tree


6
3
4
63
Binary Expression TreesEvaluate this expression
tree


6
3
4
(3 4) 6
64
Binary Expression TreesPre-order and Post-order
give the pre-fix and post-fix form of the equation
346 pre-fix


6
346 post-fix
3
4
65
Convert (AB) (C D) to postfix
66
Convert (AB) (C D) to postfixconvert the
inner expressions
67
Convert (AB) (C D) to postfixconvert the
inner expressions(AB) (CD-)
68
Convert (AB) (C D) to postfixconvert the
inner expressions(AB) (CD-)Now convert the
69
Convert (AB) (C D) to postfixconvert the
inner expressions(AB) (CD-)Now convert the
ABCD-
70
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
71
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()) . . .

72
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()) . . .

73
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())

74
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())

75
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

76
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())

77
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.

78
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

79
What does this have to do with computer
programming?
80
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

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

82
The Stack class
  • push(E item)
  • // pushes item onto the top of the stack
  • // returns item
  • pop()
  • // removes and returns the element at the top of
    the stack
  • peek()
  • // returns the element at the top of the stack
  • // throws an exception if the stack is empty
  • boolean isEmpty()
  • To Use the Stack class that implements this
    interface, you will need to
  • import java.util.

83
What is the output?
  • import java.util.
  • public class StackDemo
  • public static void main(String args)
  • Stack ltIntegergt s new Stack ltIntegergt
    ()
  • s.push(5)
  • s.push(3)
  • s.push(2)
  • s.pop()
  • System.out.println(s.peek())
  • s.pop()
  • int nNum s.pop()
  • System.out.println(nNum)

84
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 ltCharactergts new StackltCharactergt()
  • for(int nI 0 nI lt sForward.length() nI)
  • s.push(sForward.charAt(nI))
  • while(!s.isEmpty())
  • sBackward s.pop()
  • System.out.println(sBackward)
  • //Displays !amanaP !lanaC A !nalP A !naM A

85
What is the output?
  • Stack ltIntegergt s new StackltIntegergt()
  • int nX 2, nY 3
  • s.push(nX)
  • s.push(2nY)
  • s.push(4)
  • nY s.pop()
  • s.push(7)
  • s.pop()
  • nX s.peek()
  • while(!s.isEmpty())
  • System.out.println(s.pop())
  • System.out.println("nX is " nX)

86
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

87
The Queue interface
  • boolean add(E obj)
  • // enqueues obj at the end of the queue returns
    true
  • remove()
  • // dequeues and returns the element at the front
    of the queue
  • peek()
  • // returns the element at the front of the queue
  • // null if the queue is empty
  • boolean isEmpty()
  • The Queue interface is "built on top of" the
    LinkedList class
  • To Use the Queue interface you will need to
  • import java.util.

88
The Queue interface is "built on top of" the
LinkedList class
  • import java.util.
  • public class QueueDemo
  • public static void main(String args)
  • Queue ltIntegergtq new LinkedListltIntegergt()
  • q.add(5)
  • q.add(3)
  • q.add(2)
  • q.remove()
  • System.out.println(q.peek())

89
What is the output of this program?
  • Queue ltIntegergtq new LinkedList ltIntegergt ()
  • int nX 2, nY 3
  • q.add(nX)
  • q.add(2nY)
  • q.add(4)
  • nY q.remove()
  • q.add(7)
  • q.remove()
  • nX q.peek()
  • while(!q.isEmpty())
  • System.out.println(q.remove())
  • System.out.println("nX is " nX)

90
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?

91
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"

92
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 gt 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
93
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
94
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)

95
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
96
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
97
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
98
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
99
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
100
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
101
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
102
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
103
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
104
The PriorityQueue class
  • boolean add(E obj)
  • // adds obj to the priority queue returns true
  • remove()
  • // removes and returns the minimal element from
    the priority queue
  • peek()
  • // returns the minimal element from the priority
    queue
  • // null if the priority queue is empty
  • boolean isEmpty()
  • The PriorityQueue class only works with
    Comparable items that implement Comparable
  • To Use the PriorityQueue interface you will need
    to
  • import java.util.

105
What is the output?
  • import javal.util.
  • public class PriorityQueueDemo
  • public static void main(String args)
  • PriorityQueue ltIntegergtpq
  • new PriorityQueue ltIntegergt ()
  • pq.add(5)
  • pq.add(2)
  • System.out.println(pq.peek())
  • pq.add(-3)
  • while(!pq.isEmpty())
  • System.out.println(pq.remove())

106
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)

107
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

108
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

109
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

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

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

112
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())

113
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)

114
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()gt2)
  • i.set(temp.toUpperCase())
  • i l.listIterator()
  • while(i.hasNext())
  • System.out.println(i.next())

115
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())

116
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()
  • //note no ListIterator

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

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

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

120
TreeSet vs. HashSet
  • HashSet is faster, but unsorted
  • HashSet is O(1) for add, remove and contains
  • Iterating through a HashSet gives items in no
    particular order
  • Data placed into hash table using hashCode()
  • 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
  • Data placed into BST using compareTo() cannot be
    used with Objects that don't have a compareTo()
    method defined

121
The Map interface
  • Implemented by HashMap and TreeMap
  • Each item must have unique "key"
  • No iterator! (e.g. you have to get the set of
    Keys)
  • 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()

122
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 ltString, Stringgt h
  • new HashMap ltString, Stringgt ()
  • 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"))

123
Using a TreeMap is identical
  • import java.util.
  • public class HashDemo
  • public static void main(String args)
  • Map ltString, Stringgt h
  • new TreeMap ltString, Stringgt ()
  • 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"))

124
Sets vs. Maps
  • If you want to be able to associate an individual
    object with some arbitrary value, use a Map
  • If you want to deal with items as a group,
    without regard to order or duplication, use a Set
  • 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

125
Hashes vs. Trees
  • Both Sets and Maps are implemented with either a
    Hash or a Binary Search Tree
  • BSTs are sorted, Hashes aren't
  • You can only use a Tree with Objects that
    implement Comparable, that is have a compareTo()
    method
  • All Objects have a hashCode() method, so you can
    always use a Hash

126
What is the output?
  • Set ltStringgt mysterySet1 new TreeSetltStringgt()
  • mysterySet1.add("coconut")
  • mysterySet1.add("banana")
  • mysterySet1.add("apple")
  • Map ltInteger, Set ltStringgtgt mysteryMap
  • new TreeMapltInteger,SetltStringgtgt()
  • mysteryMap.put(1,mysterySet1)
  • mysteryMap.put(2,null)
  • Set ltIntegergt keys mysteryMap.keySet()
  • for(Integer i keys)
  • Set ltStringgt s mysteryMap.get(i)
  • if(mysteryMap.get(i)null)
  • s new TreeSet ltStringgt()
  • s.add("durian")
  • System.out.println(s)
Write a Comment
User Comments (0)
About PowerShow.com