Professional Documents
Culture Documents
Bitstream 1668140 PDF
Bitstream 1668140 PDF
Bitstream 1668140 PDF
00 Tutorial 10
1
Topics
Trees
Binary Trees
Binary Search Trees
Problem Set 9
2
Tree Terminology
root Bs parent
Ds ancestors
A B
As descendants C D E F
or the subtree
rooted at C Bs children
G H
leaves
3
Binary Tree Examples
1. 2. 3.
root root root
A B B
C D
4
Tree Traversal
Visiting all nodes of a binary tree just once
5
Tree Traversal Exercise
*
3.14159 ^
/ 2
+ 2
6 *
3 1.17
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?
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);
}
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 25
7 16 19 32
8 12 17 27 33
29
11
How does delete() work?
18
11 25
7 16 19 32
8 12 17 27 33
first() of
right subtree 29
12
delete(), replace successor 1
18
11 25
7 16 19 32
8 12 17 27 33
29
13
delete(), replace successor 2
18
11 25 27
7 16 19 32
8 12 17 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