Professional Documents
Culture Documents
Lecture 4
Trees
Trees
A tree consists of:
● A set of nodes.
● A set of edges which connect pairs of nodes.
Requirements:
● Connected - there is a path from any node to another node along the edges.
● If there are N nodes, there are N-1 edges.
Can be rephrased as: there is exactly one path between each pair of nodes.
Common Example: File Folders
/home/alanyao
lectures/ labs/
Trees
Rooted tree definitions:
/home/alanyao
lectures/ labs/
leaves
Trees
Rooted tree metrics:
Height:
3 games/ images/ downloads/ school/
Depth:
1
lectures/ labs/
Height:
0
Trees: Traversals: Preorder
class TreeNode { 1
void preorder() {
this.visit(); //do something
2 6
children.forEach(this::preorder);
}
}
3 4 5 7 8
void postorder() {
children.forEach(this::postorder);
4 7
this.visit(); //do something
}
}
1 2 3 5 6
5
Binary Search Trees: Operations
Other typical Map<K, V> operations.
● insert(K, V)
● remove(K)
● min(), max()
● getAllGreaterThan(K), getAllLessThan(K)
● getNthLargest(int n)
LinkedList
ArrayList
(resizing array)
TreeSet
(balanced BST)
Review: How fast are add and contains?
ArrayList
(resizing array)
TreeSet 2 1 9
(balanced BST)
Review: How fast are add and contains?
0 1 2 3 4 5 6 7
F T T T T F F F
Problems?
Can we do better?
● Specifically, imagine data structure that holds just whole numbers. Can we
make add and contains faster?
● Yes! BooleanSet in lab09 is already faster! ϴ(1) add and contains!
0 1 2 3 4 5 6 7
F T T T T F F F
Problems!
You’ll need a huge array! Lots of wasted space!
Solution?
Can we do better?
Solution!
● Rather than placing booleans in each array spot, place the number itself.
● Wrap the numbers using modular arithmetic! (e.g. 8 mod 8 ≣ 0)
0 1 2 3 4 5 6 7
8 9 -1 3 12 5 -1 -1
Problems?
Can we do better?
Solution!
● Rather than placing booleans in each array spot, place the number itself.
● Wrap the numbers using modular arithmetic! (e.g. 8 mod 8 ≣ 0)
0 1 2 3 4 5 6 7
8 9 -1 3 12 5 -1 -1
Problems!
What happens if you want to add both 0 and 8 in the array? Collision!
Solution?
Can we do better?
Solution! 0 1 2 3 4 5 6 7
0 4
Solution?
Can we do better?
General runtime: 0 1 2 3 4 5 6 7
● ϴ(1) add
● ϴ(linked list length) contains
8 9 3 12 5
Solution!
● Resize array as elements are added
0 4
so that linked list length remains
constant.