Sie sind auf Seite 1von 3

1

1.00 Tutorial 10
2
Topics
? Trees
? Binary Trees
? Binary Search Trees
? Problem Set 9
These are today?s topics
3
root
A
B
C
B?s parent
D?s ancestors
B?s children
A?s descendants
or the subtree
rooted at C
leaves
G H
D E F
Tree Terminology
Define root, ancestors, descendants, children, leaf nodes
4
1.
root
3.2.
root root
A B
B
DC
F
E
Binary Tree Examples
Binary trees can be of all these forms.
A linked list is an extreme example of binary tree.
5
Tree Traversal
Visiting all nodes of a binary tree just once
? Pre-Order: Root, Left, Right
? In-Order: Left, Root, Right
? Post-Order: Left, Right, Root
6
Tree Traversal Exercise
*
3.14159 ^
2
/
2+
6
*
3
1.17
What do the three traversals give for this Parse-Tree?
Connection between the parse tree and a stack based calculator.
7
Binary Search Trees
? The left subtree of every node (if it exists) must only
contain nodes with keys less than or equal to the parent
and the right subtree (if it exists) must only contain nodes
with keys greater than or equal to the parent.
? In-Order traversal visits each node in order
?Exercise:
Create a BST of 5, 3, 7, 9, 2, 4, 8, 1 Verify with a In-Order
Traversal. What is the algorithm used in creating the BST?
Now create a BST of 1, 2, 3, 5, 7, 8, 9. What happened?
We get a linked list! Introduce the concept of a balanced search tree.
8
Maps, SortedMaps
? Maps are data structures which contains
(Key, Value) pairs.
? A BST is a SortedMap where we sort according to
the keys and we allow no duplicate keys.
(Duplicate Values are fine)
9
Comparing Objects
public interface Comparator
{
// Neither o1 nor o2 may be null
public int compare(Object o1, Object o2);
}
public interface Comparable
{
public int compareTo(Object o);
}
Explain the Comparator and Comparable interfaces.
10
BST implements SortedMap
public interface SortedMap {
// keys may not be null but values may be
public boolean isEmpty();
public void clear();
public int size();
public Object get( Object key );
public Object firstKey();
public Object lastKey();
public Object remove( Object key );
public Object put( Object key, Object value );
public MapIterator iterator();
}
11
How does firstKey() work?
18
11 25
7 16 19
12 17
32
29
3327
1
st
iteration
2
nd
iteration
8
12
How does delete() work?
18
11 25
7 16 19
12 17
32
3327
29
8
first() of
right subtree
13
delete(), replace successor 1
18
11
25
7 16 19
12 17
32
3327
29
8
14
delete(), replace successor 2
18
11
25
7 16 19
12 17
32
3327
29
8
27
15
Problem Set 9
Grading:
1. Completeness of Description 50%
2. Scalability 20%
3. Convergence 20%
4. Likely Quality of Outcome 10%
Program Design: Think about and document
? The Classes and their public interfaces
? Data structures
? Do not worry about implementation right now.
Think about your algorithm
? Does it terminate?
? Does it finish in reasonable time?
? Can you compute O() for your algorithm to see how it scales?

Das könnte Ihnen auch gefallen