1.00 Tutorial 10 1

advertisement
1.00 Tutorial 10
1
Topics
•
•
•
•
Trees
Binary Trees
Binary Search Trees
Problem Set 9
These are today’s topics
2
Tree Terminology
root B’s parent
D’s ancestors
A
A’s descendants
or the subtree
rooted at C
G
C
B
D
E
F
B’s children
H
leaves
Define root, ancestors, descendants, children, leaf nodes
3
Binary Tree Examples
1.
2.
root
A
root
3.
root
B
B
C
D
E
F
Binary trees can be of all these forms.
A linked list is an extreme example of binary tree.
4
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
5
Tree Traversal Exercise
*
^
3.14159
2
/
+
6
2
*
3
1.17
What do the three traversals give for this Parse-Tree?
Connection between the parse tree and a stack based calculator.
6
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.
7
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)
8
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.
9
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();
}
10
How does firstKey() work?
1st iteration
18
2nd iteration
11
7
25
16
8
12
19
17
32
27
33
29
11
How does delete() work?
18
11
7
25
16
8
12
19
17
first() of
right subtree
32
27
33
29
12
delete(), replace successor 1
18
25
11
7
16
8
12
19
17
32
27
33
29
13
delete(), replace successor 2
18
25
11
7
16
8
12
27
19
17
32
27
33
29
14
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?
15
Download