Title: Today
1Todays Objectives
Week 11
- Announcements
- Hand in Homework 3
- Submit the topic for your presentation
- Quiz 3 is next week, 10-Apr
- It will include questions about trees and binary
trees - Some simple Java, for example, instantiate an
object of a tree class - Several questions about tree terminology, depth,
and height - Several tree traversal problems, like the
problems on the handouts - Tree Traversals and Binary Trees (from last
weeks slides)? - Review creating a tree, adding a node, and
traversals (demo and p. 294)? - Binary tree implemented with an ArrayList
- Binary Search Trees
- Intro to AVL Trees
- Bonus Lab 4
- Using diamond.rocks.cl.uh.edu, the UNIX remote
login system at UHCL
2Trees
3Terminology
Trees (Goodrich, 268)?
Siblings _____________________
r
Internal node(s) ______________________ Externa
l node(s) ______________________
s
t
v
v
w
x
This is a ________________ rooted at v
Ancestors of v _________________________________
____ Descendents of v __________________________
___________
4Binary Tree
Trees (Goodrich, 282)?
- Every node has at most two children
r
t is the ______ ______ of r
s is the ______ ______ of r
s
t
Is this a proper binary tree? Why or why not?
5Another Tree Problem
Trees
- What is the inorder traversal?
10
15
4
11
80
3
8
7
9
20
33
27
24
6Binary Search Trees
7Binary Search Tree (BST)?
Trees (Goodrich, 301, 418)?
- A specialized binary tree
- Data are arranged in an order that allows us to
search for it easily - Each internal node v stores an element e
- Elements in the left subtree of v ? e
- Elements in the right subtree of v ? e
- Assume that the external nodes are empty and the
tree is a proper binary tree
7
11
3
9
13
1
5
8Searching in a BST
Trees (Goodrich, 414416)?
- Write an algorithm in pseudocode that searches a
BST for the key value 9 - Algorithm TreeSearchFor9( pos )?
- If pos is external then 9 isnt here - return
null - If 9 lt pos.getValue() then TreeSearchFor9(leftSub
tree)? - Else if 9 gt pos.getValue() TreeSearchFor9(rightSu
btree)? - Else pos contains 9 and we found it return pos
7
11
3
9
13
1
5
9Searching in a BST
Trees (Goodrich, 419)?
- Write an algorithm in pseudocode that searches a
BST for the key value 4 - Algorithm TreeSearchFor4( pos )?
- If pos is external then 4 isnt here - return
null - If 4 lt pos.getValue() then TreeSearchFor4(leftSub
tree)? - Else if 4 gt pos.getValue() TreeSearchFor4(rightSu
btree)? - Else pos contains 4 and we found it return pos
7
11
3
9
13
1
5
10TreeSearch Algorithm
Trees (Goodrich, 419)?
- Algorithm TreeSearch( target, v )?
- IN target key to search for
- v node to start the search
- OUT Node w that is either the target or an
external node where the target should go - if v is external node then return v
- if target lt v.getValue() then
- return TreeSearch( target, left(v) )?
- else if target gt v.getValue() then
- return TreeSearch( target, right(v) )?
- else return v
What is the Big-Oh?
11Best Case and Worst Case
Trees (Goodrich, 424)?
Number of elements stored 7
Best Case O( logn )?
7
11
3
n number of nodes n 15 h log(n1) 1 3
9
13
1
5
Worst Case O( n )?
1
3
n 15 h (n1)/2 7
5
7
What circumstances cause the tree to look like
this?
9
11
13
12Experimental Results
Trees
Linear growth in runtime of find()?
f(n)? Time in seconds to find 50,000 elements
Logarithmic growth in runtime of find()?
Random int data inserted into the tree
Sorted int data inserted into the tree
Testing find() with BinarySearchTree
13Key
Trees (Goodrich, 320321)?
- An attribute that
- 1. Can be ordered
- 2. Can be used to identify an element
- Must be able to put it in an order or rank
i.e., we must be able to compare two keys and
determine whether one is larger than the other - Can be externally generated and assigned
- Examples
- Student ID used to identify students
- Social security number used to identify workers
in the U.S. - Account ID used to identify an account holder
- ISBN used to identify a book
- Call number used to identify a library resource
14BST Stores Keys
Trees (Goodrich, 418)?
- The data itself can be its own key
D
These letters are data that we can put into an
order based on their ASCII code.
F
B
E
G
A
C
- The keys may represent other data
6274
These are account numbers that can be ordered,
and they represent records containing additional
data.
8837
2843
9523
1892
4892
15(No Transcript)
16Entry Interface
Trees (Goodrich, 322)?
public interface EntryltK,Vgt / Returns the
key stored in this entry. / public K
getKey() / Returns the value stored in this
entry. / public V getValue()
17BSTEntry Class
Trees (Goodrich, 426)?
- protected static class BSTEntryltK,Vgt implements
EntryltK,Vgt - protected K key
- protected V value
- protected PositionltEntryltK,Vgtgt pos
- BSTEntry()
- BSTEntry(K k, V v, PositionltEntryltK,Vgtgt p)
- key k value v pos p
-
- public K getKey() return key
- public V getValue() return value
- public PositionltEntryltK,Vgtgt position()
return pos
18BST that Stores BSTEntry Objects
Trees
- key account ID
- value record number
6274 0
8837 3
2843 1
9523 5
1892 4
4892 2
19BinarySearchTree Class
Trees (Goodrich, 426428)?
- Public Operations
- int size()?
- boolean isEmpty()?
- position find( key )?
- iterator findAll( key )?
- void insert( key, element )?
- void remove( key )?
- All public operations in the LinkedBinaryTree
- Instance Variables
- Comparator C
- All public instance variables in the
LinkedBinaryTree class - Create an object of the BinarySearchTree class
- BinarySearchTreeltString,Integergt index
- new BinarySearchTreeltString
,Integergt()
Datatype of the keys
Datatype of the values
20Comparing Objects
Trees (Goodrich, 323324 Horstmann, 101)?
- How does the BinarySearchTree know how you want
the elements sorted? - ANSWER It uses a comparator to determine which
object is smaller. - One of the instance variables in the
BinarySearchTree class - The default comparator in BinarySearchTree
assumes that the objects stored in the tree
implement the Comparable interface - Any object that implements Comparable already has
a compareTo method that the comparator can call - We may need to implement a custom comparator
class, which can be passed to the
BinarySearchTree constructor
21Comparator compares the keys
Trees (Goodrich, 323324 Horstmann, 101)?
- A class used to compare two keys
- Implements the Comparator interface, which
defines only one method - int compare(Object a, Object b)
- Generalizes a data structure so that we can
compare non-numeric keys - Example
- MyComparatorltKgt c new MyComparatorltEgt()
- int result c.compare( a, b )
- If object a is less than object b, return a
negative integer - If object a is greater than object b, return a
positive integer - If theyre equal, return 0
22DefaultComparator Class
Trees (Goodrich, 426428)?
- The default comparator for the BinarySearchTree
class - / Compares two given elements
-
- _at_return a negative integer if a is less than
b, - zero if a equals b, or a positive integer if
- a is greater than b
- /
- public class DefaultComparatorltEgt implements
ComparatorltEgt - public int compare(E a, E b) throws
ClassCastException - return ((ComparableltEgt) a).compareTo(b)
-
23TreeSearch Implementationby treeSearch()
called by find()?
Trees (Goodrich, 427)?
- //Algorithm TreeSearch( target, v )?
- // if v is external node then return v
- // else if target lt v.element() then
- // return TreeSearch( target, leftChild(v) )?
- // else if target gt v.element() then
- // return TreeSearch( target, rightChild(v) )?
- // else return v
- protected PositionltEntryltK,Vgtgt treeSearch(K key,
PositionltEntryltK,Vgtgt pos) - if (isExternal(pos)) return pos // key not
found return external node - else
- K curKey key(pos)
- int comp C.compare(key, curKey)
- if (comp lt 0)
- return treeSearch(key, left(pos)) //
search left subtree - else if (comp gt 0)?
- return treeSearch(key, right(pos)) //
search right subtree - return pos // return internal node where
key is found -
24Searching a BST with find()?
Trees
- //First, create an empty entry for the result
- EntryltString,Integergt entry null
- //more code ...
- //Get a key to search for
- System.out.println("Enter Account ID ")
- String searchID myBufferedReader.readLine()
- //Search by calling find()?
- entry index.find( searchID )
- if(entry null) System.out.println("Not found")
25Using the Entry Object
Trees
- Once we have the Entry object for a node in the
BST, its methods make it easy for us to get the
value or the key - Example
- long recordNum (Long)(entry.getValue())
26InsertingKey 4892, Element 2
Trees (Goodrich, 417)?
6274 0
8837 3
2843 1
27InsertingKey 4892, Element 2
Trees (Goodrich, 421, 427428)?
- Find the position of an external node where the
key should be inserted
p treeSearch( 4892, root() )
6274 0
8837 3
2843 1
28InsertingKey 4892, Element 2
Trees (Goodrich, 421, 427428)?
- Find an external node where the key should be
inserted - Expand the node
expandExternal(p,null,null)
6274 0
8837 3
2843 1
insertLeft(p,null)
insertRight(p,null)
29InsertingKey 4892, Element 2
Trees (Goodrich, 421, 427428)?
- Find an external node where the key should be
inserted - Expand the node
- Add the key and element at the node
6274 0
8837 3
2843 1
4892 2
replace(p,e)
30Inserting Implemented in the BinarySearchTree
Class
Trees (Goodrich, 421, 427428)?
- //Find an external node where the key should be
inserted - //Expand the node
- //Add the key and element at the node
- public EntryltK,Vgt insert(K k, V x) throws
InvalidKeyException - checkKey(k)
- PositionltEntryltK,Vgtgt insPos treeSearch(k,
root()) - //If insPos is internal, a duplicate key is in
the tree, so - //if dupes are allowed, keep looking for a
place to put it - while (!isExternal(insPos))?
- insPos treeSearch(k, left(insPos))
- actionPos insPos //save this position for
later - return insertAtExternal(insPos, new
BSTEntryltK,Vgt(k, x, insPos))
31Inserting Implemented in the BinarySearchTree
Class
Trees (Goodrich, 421, 427428)?
- //Find an external node where the key should be
inserted - //Expand the node
- //Add the key and element at the node
- public EntryltK,Vgt insert(K k, V x) throws
InvalidKeyException - checkKey(k)
- PositionltEntryltK,Vgtgt insPos treeSearch(k,
root()) - //If insPos is internal, a duplicate key is in
the tree, so - //if dupes are allowed, keep looking for a
place to put it - while (!isExternal(insPos))?
- insPos treeSearch(k, left(insPos))
- actionPos insPos //save this position for
later - return insertAtExternal(insPos, new
BSTEntryltK,Vgt(k, x, insPos))
32Inserting Implemented in the BinarySearchTree
Class
Trees (Goodrich, 421, 427428)?
- protected EntryltK,Vgt insertAtExternal(PositionltEnt
ryltK,Vgtgt v,
EntryltK,Vgt e)
- expandExternal(v,null,null)
- replace(v, e)
- numEntries
- return e
-
33Removing Key 4892
Trees (Goodrich, 422)?
- Use find(K) to get an Entry object that
represents the node that contains the key - Then extract its position in remove(E), call it
remPos
6274 0
8837 3
2843 1
remPos
9523 5
1892 4
4892 2
3165 6
34Removing Key 4892
Trees (Goodrich, 422)?
- Use find(K) to get an Entry object that
represents the node that contains the key - Then extract its position in remove(E), call it
remPos - If one of the nodes children is external assign
it the name remPos and call the
removeAboveExternal(remPos) method
6274 0
8837 3
2843 1
9523 5
1892 4
4892 2
remPos
3165 6
35Removing Key 4892
Trees (Goodrich, 422)?
- removeAboveExternal(remPos)(a LinkedBinaryTree
method) renames the nodes, and then calls
remove(v) first and remove(u) next
6274 0
8837 3
2843 1
u
9523 5
1892 4
4892 2
v
3165 6
36Removing Key 4892
Trees (Goodrich, 422)?
- removeAboveExternal(remPos)(a LinkedBinaryTree
method) renames the nodes, and then calls
remove(v) first and remove(u) next - remove(pos) reassigns the links so that the
sibling of v takes the place of u in the tree
6274 0
8837 3
2843 1
9523 5
1892 4
3165 6
37Removing Implemented in the BinarySearchTree Class
Trees (Goodrich, 428)?
- //Find the position of the node that contains the
key with finder, call it r - //If one of the nodes children is external,
remove the node and replace it - // with the sibling of its external child
- //If both of rs children are internal
- // Find the left-most node in rs right subtree,
call it p - // Move the contents of ps parent into r
- // Remove p and ps parent
- public EntryltK,Vgt remove(EntryltK,Vgt ent) throws
InvalidEntryException - checkEntry(ent)
- PositionltEntryltK,Vgtgt remPos
((BSTEntryltK,Vgt) ent).position() - EntryltK,Vgt toReturn entry(remPos)
- if (isExternal(left(remPos))) remPos
left(remPos) - else if (isExternal(right(remPos))) remPos
right(remPos) - else
- PositionltEntryltK,Vgtgt swapPos remPos
- remPos right(swapPos)
- do
- remPos left(remPos)
38Removing Key 2843
Trees (Goodrich, 422)?
6274 0
swapPos
8837 3
2843 1
9523 5
1892 4
4892 2
3165 6
39Removing Key 2843
Trees (Goodrich, 422)?
- Rename remPos to swapPos
- Name its right child remPos
6274 0
swapPos
8837 3
2843 1
remPos
9523 5
1892 4
4892 2
3165 6
40Removing Key 2843
Trees (Goodrich, 422)?
- Rename remPos to swapPos
- Name its right child remPos
- While remPos is an internal node, name its left
child remPos
6274 0
swapPos
8837 3
2843 1
9523 5
1892 4
4892 2
3165 6
remPos
41Removing Key 2843
Trees (Goodrich, 422)?
- Rename remPos to swapPos
- Name its right child remPos
- While remPos is an internal node, name its left
child remPos - Swap the parent of remPos with swapPos
6274 0
swapPos
8837 3
3165 6
9523 5
1892 4
4892 2
2843 1
remPos
42Removing Key 2843
Trees (Goodrich, 422)?
- Rename remPos to swapPos
- Name its right child remPos
- While remPos is an internal node, name its left
child remPos - Swap the parent of remPos with swapPos
- removeAboveExternal(remPos)?
6274 0
swapPos
8837 3
3165 6
9523 5
1892 4
4892 2
43Removing Implemented in the BinarySearchTree Class
Trees (Goodrich, 428)?
- //Find the position of the node that contains the
key with finder, call it r - //If one of the nodes children is external,
remove the node and replace it - // with the sibling of its external child
- //If both of rs children are internal
- // Find the left-most node in rs right subtree,
call it p - // Move the contents of ps parent into r
- // Remove p and ps parent
- public EntryltK,Vgt remove(EntryltK,Vgt ent) throws
InvalidEntryException - checkEntry(ent)
- PositionltEntryltK,Vgtgt remPos
((BSTEntryltK,Vgt) ent).position() - EntryltK,Vgt toReturn entry(remPos)
- if (isExternal(left(remPos))) remPos
left(remPos) - else if (isExternal(right(remPos))) remPos
right(remPos) - else
- PositionltEntryltK,Vgtgt swapPos remPos
- remPos right(swapPos)
- do
- remPos left(remPos)
44Binary Search Tree Visualizations
Trees (Goodrich, 428)?
- http//www.cs.jhu.edu/goodrich/dsa/trees/btree.ht
ml - http//www.ibr.cs.tu-bs.de/courses/ss98/audii/appl
ets/BST/BST-Example.html
45Intro to AVL Trees
46AVL Tree
AVL Trees (Goodrich, 429, Gilberg, 348)?
- Invented in 1962 by two Russian mathematicians
- G. M. Adelson-Velskii
- E. M. Landis
- A binary search tree that maintains a
height-balance property - Height-balance property
- For every internal node, the heights of its
children differ by at most 1 - Also called a height-balanced tree
47Height-Balance Property
AVL Trees (Goodrich, 429)?
- For every internal node, the heights of its
children differ by at most 1 - Consequences
- Keeps the overall height small
- Every subtree of an AVL tree is also an AVL tree
4
18
23
12
2
3
20
44
14
2
1
1
0
19
21
0
0
0
0
1
1
0
0
48Advantage
AVL Trees (Goodrich, 429, Gilberg 348349)?
- Searching in a height-balanced tree is more
efficient
n 8 for both trees (where n number of data
elements)?
AVL tree
8
23
12
18
44
14
20
52
12
18
14
8
20
23
maximum number of comparisons 3 or 4
44
O(logn)?
52
maximum number of comparisons 8
O(n) in the worst case
49Balancing
AVL Trees (Goodrich, 429)?
- Balance factor
- Height of the left child minus the height of the
right child - A node is balanced if its balance factor is -1,
0, or 1 - Insertion or removal of nodes can cause a
balanced tree to become unbalanced - After a node is inserted or removed, a
restructure operation must be invoked to
rebalance the tree
50AVLNode Class
AVL Trees (Goodrich, 438439)?
- Objects of this nested class are stored in the
nodes of an AVL tree - Since it inherits from BTNode, it has key and
value fields - protected static class AVLNodeltK,Vgt extends
BTNodeltEntryltK,Vgtgt - protected int height //we add a height field
to a BTNode - AVLNode()
- AVLNode(EntryltK,Vgt element, BTPositionltEntryltK,V
gtgt parent, - BTPositionltEntryltK,Vgtgt left,
BTPositionltEntryltK,Vgtgt right) - super(element, parent, left, right)
- height 0
- if (left ! null)
- height Math.max(height, 1
((AVLNodeltK,Vgt)left).getHeight()) - if (right ! null)
- height Math.max(height, 1
((AVLNodeltK,Vgt) right).getHeight()) -
- public void setHeight(int h) height h
- public int getHeight() return height
51AVLTree Class
AVL Trees (Goodrich, 438439)?
- Inherits from the BinarySearchTree class, so it
has all the BST methods and instance variables - Adds only two new public member functions
- public class AVLTreeltK,Vgt extends
BinarySearchTreeltK,Vgt implements DictionaryltK,Vgt
- //...other code inserted here
- protected int height(PositionltEntryltK,Vgtgt p)
//... - protected void setHeight(PositionltEntryltK,Vgtgt
p //... - protected boolean isBalanced(PositionltEntryltK,Vgt
gt p) //... - protected PositionltEntryltK,Vgtgt
tallerChild(PositionltEntryltK,Vgtgt p) //... - protected void rebalance(PositionltEntryltK,Vgtgt
zPos) //... - public EntryltK,Vgt insert(K k, V v) throws
InvalidKeyException - EntryltK,Vgt toReturn super.insert(k, v)
- rebalance(actionPos) // rebalance up from
the insertion position - return toReturn
-
- public EntryltK,Vgt remove(EntryltK,Vgt ent) throws
InvalidEntryException - EntryltK,Vgt toReturn super.remove(ent)
- if (toReturn ! null)?
- rebalance(actionPos)
- return toReturn
52Rebalancing
AVL Trees (Goodrich, 428432, 435)?
- When a new node is added, the heights of some of
the existing nodes in the tree may change
myAVLTree.insert(4,4)
4
23
2
3
18
44
12
20
52
2
1
1
0
8
14
0
0
0
0
1
1
0
0
53Rebalancing
AVL Trees (Goodrich, 428432, 435)?
- When a new node is added, the heights of some of
the existing nodes in the tree may change - All of the height changes occur along the path
from the new node w to the root
5
23
2
4
18
44
12
20
52
3
1
1
0
8
14
0
0
0
0
2
1
w
4
1
0
0
54Rebalancing
AVL Trees (Goodrich, 428432, 435)?
- The rebalance function searches for the first
unbalanced node by following the path from w to
the root - The first unbalanced node it finds is labelled z
in this figure
5
23
z
2
4
18
44
12
20
52
3
1
1
0
8
14
0
0
0
0
2
1
w
4
1
0
0
55(No Transcript)
56Rotation
AVL Trees (Goodrich, 434)?
- A term used to describe the restructuring
operation - Single rotation used in Cases 1 and 2
18
12
18
12
20
8
4
14
20
8
14
4
57(No Transcript)
58AVL Tree Visualizations
Trees (Goodrich, 428)?
- http//webpages.ull.es/users/jriera/Docencia/AVL/A
VL20tree20applet.htm - http//www.site.uottawa.ca/stan/csi2514/applets/a
vl/BT.html
59Algorithm Practice
60Sample Algorithm Question 1
Trees
- Using the operations in the Binary Search Tree
class and in the Queue ADT, write an algorithm in
pseudocode that receives a queue of chars, puts
all of its chars into a binary search tree, and
then returns a copy of the tree. - Algorithm BuildTreeFromCharQueue( Q )?
- Input One queue Q containing chars
- Output A binary search tree that contains all
the elements from the queue
61Sample Algorithm Question 2
Trees
- Using the operations in the Binary Search Tree
class, the Entry class, and the Queue ADT, write
an algorithm in pseudocode that receives a queue
of Entry objects, puts all of them into a binary
search tree, and then returns a copy of the tree.
- Algorithm BuildTreeFromEntryQueue( Q )?
- Input One queue Q containing Entry objects
- Output A binary search tree that contains all
the Entry objects from the queue
62Sample Algorithm Question 3
Trees
- Write an algorithm in pseudocode that receives a
valid expression tree, evaluates the expression,
and then returns the result. Assume that each
internal node in the expression tree contains an
operator, and the only operators allowed are
and , also assume that each external node
contains an integer. (Hint One possible solution
is on the next slide)? - Algorithm EvaluateExpressionTree( T )?
- Input A tree T that is a valid expression tree
- Output The result of evaluating the expression
theRoot
Example
2
3
4
63One possible solution
Trees (Sedgewick, 149)?
- //Function definition
- PostorderTraversal( BinaryTree T, Position v,
Queue Q ) - if( T.isInternal(v) ) PostorderTraversal( T,
T.left(v), Q )? - if( T.isInternal(v) ) PostorderTraversal( T,
T.right(v), Q )? - Q.enqueue( v.element() )?
-
- Queue Q1
- PostorderTraversal( T, T.root(), Q1 )?
- Stack st
- while not Q1.isEmpty()?
- if Q1.front() '' then
- Q1.dequeue()?
- st.push( st.pop() st.pop() )?
- else if Q1.front() '' then
- Q1.dequeue()?
- st.push( st.pop() st.pop() )?
- else
64References
- Gilberg, R. F. and B. A. Forouzan, Data
Structures, A Pseudocode Approach with C. Boston
PWS Publishing Company, 1998. - Goodrich, M. T. and R. Tamassia, Data Structures
and Algorithms in Java. Hoboken, NJ John Wiley
Sons, Inc., 2006. - Horstmann, Cay S., and Gary Cornell, Core Java 2,
Volume II-Advanced Features. Palo Alto,
California Sun Microsystems Press. - Sedgewick, R., Algorithms in C, Third Edition.
Boston Addison-Wesley, 1998. - Weiss, M. A., Data Structures and Algorithm
Analysis in C, Second Edition. Boston
Addison-Wesley, 1997.