Professional Documents
Culture Documents
Data Structures: Trees and Graphs
Data Structures: Trees and Graphs
Data Structures: Trees and Graphs
2
Binary Tree Example
84
65 96
24 50 53
48 37
Which node is the root?
Which nodes are the leaves?
Which nodes are internal nodes?
What is the height of this tree?
3
Binary Tree Example
84 Level 0
65 96 Level 1
24 50 53 Level 2
48 37 Level 3
48 37
5
Binary Trees: Implementation
65 Level 0
24 50 Level 1
48 37 14 Level 2
6
Implement Using a List
65 Level 0
24 50 Level 1
48 37 14 Level 2
7
Binary Search Tree (BST)
8
Example: Binary Search Tree
BST ordering invariant: At any node with value k,
all values of elements in the left subtree are strictly less than k and
all values of elements in the right subtree are strictly greater than k
(assuming that there are no duplicates in the tree)
4 8
1 6 9
Example: Is this a BST?
4 4
1 7 1 7
3
6 8
6 8
3 9 9
no yes
10
Insertion in a BST
¤ For each data value that you wish to insert into the binary
search tree:
¤ If you reach an empty tree (must test this first, why?), create
a new leaf node with your value at that location
¤ Recursively search the BST for your value until you either find
it or reach an empty tree
¤ If you find the value, throw an exception since duplicates
are not allowed
11
Insertion Example
¤ Insert: 84, 41, 96, 24, 37, 50, 13, 98
84
41 96
24 50 98
13 37
12
Binary Search Tree Complexity
1 Tree 2
Tree 1 6
4
6
4 8
1 5 9
8
O(log n) O(n)
9
13
Relationship Data
From this…
14
Relationship Data
To this…
C
B
F
D
A G
E
15
Graphs
16
Example Graphs
Vertex A A
C C
B B
D D
Undirected Directed
17
Graph Implementation
to to
from
A B C D from
A B C D
A 0 6 7 5 A 0 6 7 5
B 6 0 4 ∞ B ∞ 0 4 ∞
C 7 4 0 3 C 2 ∞ 0 3
D 5 ∞ 3 0 D ∞ ∞ 9 0
19
Graphs in Python
A 7
6
C
4
B
3
5
D
to
from
A B C D
vertices = ['A', 'B', 'C', 'D']
A 0 6 7 5 graph =
B 6 0 4 ∞ [ [ 0, 6, 7, 5 ],
[ 6, 0, 4, None],
C 7 4 0 3 [ 7, 4, 0, 3],
D 5 ∞ 3 0 [ 5, None, 3, 0] ]
20
Graph Algorithms
21
Shortest Path (Dijkstra's algorithm)
¤ Assign every node an initial distance (0 to the source, ∞ for all
others); mark all nodes as unvisited
22
Dijkstra example
A B C D E F G
2
D E 0 ∞ ∞ ∞ ∞ ∞ ∞
17 A->
6 7
19
B 4 F
12
2 5 6
A C G
3 4
23
Dijkstra example
A B C D E F G
2
0 ∞ ∞ ∞ ∞ ∞ ∞
D E
A-> 12 3 ∞ 17 ∞ ∞
6 17 7
C-> 5 22 17 8 7
19
B-> 11 17 8 7
B 4 F
G-> 11 17 8
12
2 5 6 F-> 11 15
A C G D-> 13
3 4 E 0 5 3 11 13 8 7
24