SlideShare a Scribd company logo
UNIT 3
Trees
All the programs in this file are selected from
Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed
“Fundamentals of Data Structures in C”,
Computer Science Press, 1992.
CHAPTER 5 2
Trees
Gill Tansey
Brunhilde
Tweed Zoe
Terry
Honey Bear
Crocus Primrose
Coyote
Nous Belle
Nugget
Brandy
Dusty
Root
leaf
CHAPTER 5 3
Definition of Tree
 A tree is a finite set of one or more nodes
such that:
 There is a specially designated node called
the root.
 The remaining nodes are partitioned into n>=0
disjoint sets T1, ..., Tn, where each of these
sets is a tree.
 We call T1, ..., Tn the subtrees of the root.
CHAPTER 5 4
Level and Depth
K L
E F
B
G
C
M
H I J
D
A
Level
1
2
3
4
node (13)
degree of a node
leaf (terminal)
nonterminal
parent
children
sibling
degree of a tree (3)
ancestor
level of a node
height of a tree (4)
3
2 1 3
2 0 0 1 0 0
0 0 0
1
2 2 2
3 3 3 3 3 3
4 4 4
CHAPTER 5 5
Terminology
 The degree of a node is the number of subtrees
of the node
– The degree of A is 3; the degree of C is 1.
 The node with degree 0 is a leaf or terminal
node.
 A node that has subtrees is the parent of the
roots of the subtrees.
 The roots of these subtrees are the children of
the node.
 Children of the same parent are siblings.
 The ancestors of a node are all the nodes
along the path from the root to the node.
CHAPTER 5 6
Representation of Trees
 List Representation
– ( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) )
– The root comes first, followed by a list of sub-trees
data link 1 link 2 ... link n
How many link fields are
needed in such a representation?
CHAPTER 5 7
Left Child - Right Sibling
A
B C D
E F G H I J
K L M
data
left child right sibling
CHAPTER 5 8
Binary Trees
 A binary tree is a finite set of nodes that is
either empty or consists of a root and two
disjoint binary trees called the left subtree
and the right subtree.
 Any tree can be transformed into binary tree.
– by left child-right sibling representation
 The left subtree and the right subtree are
distinguished.
J
I
M
H
L
A
B
C
D
E
F G
K
*Figure 5.6: Left child-right child tree representation of a tree (p.191)
CHAPTER 5 10
Abstract Data Type Binary_Tree
structure Binary_Tree(abbreviated BinTree) is
objects: a finite set of nodes either empty or
consisting of a root node, left Binary_Tree,
and right Binary_Tree.
functions:
for all bt, bt1, bt2  BinTree, item  element
Bintree Create()::= creates an empty binary tree
Boolean IsEmpty(bt)::= if (bt==empty binary
tree) return TRUE else return FALSE
CHAPTER 5 11
BinTree MakeBT(bt1, item, bt2)::= return a binary tree
whose left subtree is bt1, whose right subtree is bt2,
and whose root node contains the data item
Bintree Lchild(bt)::= if (IsEmpty(bt)) return error
else return the left subtree of bt
element Data(bt)::= if (IsEmpty(bt)) return error
else return the data in the root node of bt
Bintree Rchild(bt)::= if (IsEmpty(bt)) return error
else return the right subtree of bt
CHAPTER 5 12
Samples of Trees
A
B
A
B
A
B C
G
E
I
D
H
F
Complete Binary Tree
Skewed Binary Tree
E
C
D
1
2
3
4
5
CHAPTER 5 13
Maximum Number of Nodes in BT
 The maximum number of nodes on level i of a
binary tree is 2i-1
, i>=1.
 The maximum nubmer of nodes in a binary tree
of depth k is 2k
-1, k>=1.
i-1
Prove by induction.
2 2 1
1
1
i
i
k
k


  
CHAPTER 5 14
Relations between Number of
Leaf Nodes and Nodes of Degree 2
For any nonempty binary tree, T, if n0 is the
number of leaf nodes and n2 the number of nodes
of degree 2, then n0=n2+1
proof:
Let n and B denote the total number of nodes &
branches in T.
Let n0, n1, n2 represent the nodes with no children
single child, and two children respectively.
n= n0+n1+n2, B+1=n, B=n1+2n2 ==> n1+2n2+1= n
n1+2n2+1= n0+n1+n2 ==> n0=n2+1
CHAPTER 5 15
Full BT VS Complete BT
 A full binary tree of depth k is a binary tree of
depth k having 2 -1 nodes, k>=0.
 A binary tree with n nodes and depth k is
complete iff its nodes correspond to the nodes
numbered from 1 to n in the full binary tree of
depth k.
k
A
B C
G
E
I
D
H
F
A
B C
G
E
K
D
J
F
I
H O
N
M
L
由上至下,
由左至右編號
Full binary tree of depth 4
Complete binary tree
CHAPTER 5 16
Binary Tree Representations
 If a complete binary tree with n nodes (depth =
log n + 1) is represented sequentially, then for
any node with index i, 1<=i<=n, we have:
– parent(i) is at i/2 if i!=1. If i=1, i is at the root and
has no parent.
– left_child(i) ia at 2i if 2i<=n. If 2i>n, then i has no
left child.
– right_child(i) ia at 2i+1 if 2i +1 <=n. If 2i +1 >n,
then i has no right child.
CHAPTER 5 17
Sequential Representation
A
B
--
C
--
--
--
D
--
.
E
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
.
[16]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
A
B
C
D
E
F
G
H
I
A
B
E
C
D
A
B C
G
E
I
D
H
F
(1) waste space
(2) insertion/deletion
problem
CHAPTER 5 18
Linked Representation
typedef struct node *tree_pointer;
typedef struct node {
int data;
tree_pointer left_child, right_child;
};
data
left_child right_child
data
left_child right_child
CHAPTER 5 19
Binary Tree Traversals
 Let L, V, and R stand for moving left, visiting
the node, and moving right.
 There are six possible combinations of traversal
– LVR, LRV, VLR, VRL, RVL, RLV
 Adopt convention that we traverse left before
right, only 3 traversals remain
– LVR, LRV, VLR
– inorder, postorder, preorder
CHAPTER 5 20
Arithmetic Expression Using BT
+
*
A
*
/
E
D
C
B
inorder traversal
A / B * C * D + E
infix expression
preorder traversal
+ * * / A B C D E
prefix expression
postorder traversal
A B / C * D * E +
postfix expression
level order traversal
+ * E * D / C A B
CHAPTER 5 21
Inorder Traversal (recursive version)
void inorder(tree_pointer ptr)
/* inorder tree traversal */
{
if (ptr) {
inorder(ptr->left_child);
printf(“%d”, ptr->data);
indorder(ptr->right_child);
}
}
A / B * C * D + E
CHAPTER 5 22
Preorder Traversal(recursive version)
void preorder(tree_pointer ptr)
/* preorder tree traversal */
{
if (ptr) {
printf(“%d”, ptr->data);
preorder(ptr->left_child);
predorder(ptr->right_child);
}
}
+ * * / A B C D E
CHAPTER 5 23
Postorder Traversal (recursive version)
void postorder(tree_pointer ptr)
/* postorder tree traversal */
{
if (ptr) {
postorder(ptr->left_child);
postdorder(ptr->right_child);
printf(“%d”, ptr->data);
}
}
A B / C * D * E +
CHAPTER 5 24
Iterative Inorder Traversal
(using stack)
void iter_inorder(tree_pointer node)
{
int top= -1; /* initialize stack */
tree_pointer stack[MAX_STACK_SIZE];
for (;;) {
for (; node; node=node->left_child)
add(&top, node);/* add to stack */
node= delete(&top);
/* delete from stack */
if (!node) break; /* empty stack */
printf(“%D”, node->data);
node = node->right_child;
}
} O(n)
CHAPTER 5 25
Trace Operations of Inorder Traversal
Call of inorder Value in root Action Call of inorder Value in root Action
1 + 11 C
2 * 12 NULL
3 * 11 C printf
4 / 13 NULL
5 A 2 * printf
6 NULL 14 D
5 A printf 15 NULL
7 NULL 14 D printf
4 / printf 16 NULL
8 B 1 + printf
9 NULL 17 E
8 B printf 18 NULL
10 NULL 17 E printf
3 * printf 19 NULL
CHAPTER 5 26
Level Order Traversal
(using queue)
void level_order(tree_pointer ptr)
/* level order tree traversal */
{
int front = rear = 0;
tree_pointer queue[MAX_QUEUE_SIZE];
if (!ptr) return; /* empty queue */
addq(front, &rear, ptr);
for (;;) {
ptr = deleteq(&front, rear);
CHAPTER 5 27
if (ptr) {
printf(“%d”, ptr->data);
if (ptr->left_child)
addq(front, &rear,
ptr->left_child);
if (ptr->right_child)
addq(front, &rear,
ptr->right_child);
}
else break;
}
}
+ * E * D / C A B
CHAPTER 5 28
Copying Binary Trees
tree_poointer copy(tree_pointer original)
{
tree_pointer temp;
if (original) {
temp=(tree_pointer) malloc(sizeof(node));
if (IS_FULL(temp)) {
fprintf(stderr, “the memory is fulln”);
exit(1);
}
temp->left_child=copy(original->left_child);
temp->right_child=copy(original->right_child)
temp->data=original->data;
return temp;
}
return NULL;
}
postorder
CHAPTER 5 29
Equality of Binary Trees
int equal(tree_pointer first, tree_pointer second)
{
/* function returns FALSE if the binary trees first and
second are not equal, otherwise it returns TRUE */
return ((!first && !second) || (first && second &&
(first->data == second->data) &&
equal(first->left_child, second->left_child) &&
equal(first->right_child, second->right_child)))
}
the same topology and data
CHAPTER 5 30
Propositional Calculus Expression
 A variable is an expression.
 If x and y are expressions, then ¬x, xy,
xy are expressions.
 Parentheses can be used to alter the normal
order of evaluation (¬ >  > ).
 Example: x1  (x2  ¬x3)
 satisfiability problem: Is there an assignment to
make an expression true?




X3


X1
X2 X1
 X3
(x1  ¬x2)  (¬ x1  x3)  ¬x3
(t,t,t)
(t,t,f)
(t,f,t)
(t,f,f)
(f,t,t)
(f,t,f)
(f,f,t)
(f,f,f)
2n
possible combinations
for n variables
postorder traversal (postfix evaluation)
left_child data value right_child
typedef emun {not, and, or, true, false } logical;
typedef struct node *tree_pointer;
typedef struct node {
tree_pointer list_child;
logical data;
short int value;
tree_pointer right_child;
} ;
node structure
for (all 2n
possible combinations) {
generate the next combination;
replace the variables by their values;
evaluate root by traversing it in postorder;
if (root->value) {
printf(<combination>);
return;
}
}
printf(“No satisfiable combination n”);
First version of satisfiability algorithm
void post_order_eval(tree_pointer node)
{
/* modified post order traversal to evaluate a propositional
calculus tree */
if (node) {
post_order_eval(node->left_child);
post_order_eval(node->right_child);
switch(node->data) {
case not: node->value =
!node->right_child->value;
break;
Post-order-eval function
case and: node->value =
node->right_child->value &&
node->left_child->value;
break;
case or: node->value =
node->right_child->value | |
node->left_child->value;
break;
case true: node->value = TRUE;
break;
case false: node->value = FALSE;
}
}
}
CHAPTER 5 36
Threaded Binary Trees
 Two many null pointers in current representation
of binary trees
n: number of nodes
number of non-null links: n-1
total links: 2n
null links: 2n-(n-1)=n+1
 Replace these null pointers with some useful
“threads”.
CHAPTER 5 37
Threaded Binary Trees (Continued)
If ptr->left_child is null,
replace it with a pointer to the node that would be
visited before ptr in an inorder traversal
If ptr->right_child is null,
replace it with a pointer to the node that would be
visited after ptr in an inorder traversal
CHAPTER 5 38
A Threaded Binary Tree
A
B C
G
E
I
D
H
F
root
dangling
dangling
inorder traversal:
H, D, I, B, E, A, F, C, G
TRUE   FALSE
Data Structures for Threaded BT
typedef struct threaded_tree
*threaded_pointer;
typedef struct threaded_tree {
short int left_thread;
threaded_pointer left_child;
char data;
threaded_pointer right_child;
short int right_thread; };
left_thread left_child data right_child right_thread
FALSE: child
TRUE: thread
CHAPTER 5 40
Memory Representation of A Threaded BT
f f
--
f f
A
f f
C
f f
B
t t
E t t
F t G
f f
D
t t
I
t t
H
root
CHAPTER 5 41
Next Node in Threaded BT
threaded_pointer insucc(threaded_pointer
tree)
{
threaded_pointer temp;
temp = tree->right_child;
if (!tree->right_thread)
while (!temp->left_thread)
temp = temp->left_child;
return temp;
}
CHAPTER 5 42
Inorder Traversal of Threaded BT
void tinorder(threaded_pointer tree)
{
/* traverse the threaded binary tree
inorder */
threaded_pointer temp = tree;
for (;;) {
temp = insucc(temp);
if (temp==tree) break;
printf(“%3c”, temp->data);
}
}
O(n)
CHAPTER 5 43
Inserting Nodes into Threaded BTs
 Insert child as the right child of node parent
– change parent->right_thread to FALSE
– set child->left_thread and child->right_thread
to TRUE
– set child->left_child to point to parent
– set child->right_child to parent->right_child
– change parent->right_child to point to child
CHAPTER 5 44
Examples
root
parent
A
B
C D
child
root
parent
A
B
C D child
empty
Insert a node D as a right child of B.
(1)
(2)
(3)
*Figure 5.24: Insertion of child as a right child of parent in a threaded binary tree (p.217)
nonempty
(1)
(3)
(4)
(2)
CHAPTER 5 46
Right Insertion in Threaded BTs
void insert_right(threaded_pointer parent,
threaded_pointer child)
{
threaded_pointer temp;
child->right_child = parent->right_child;
child->right_thread = parent->right_thread;
child->left_child = parent; case (a)
child->left_thread = TRUE;
parent->right_child = child;
parent->right_thread = FALSE;
if (!child->right_thread) { case (b)
temp = insucc(child);
temp->left_child = child;
}
}
(1)
(2)
(3)
(4)
CHAPTER 5 47
Heap
 A max tree is a tree in which the key value in
each node is no smaller than the key values in
its children. A max heap is a complete binary
tree that is also a max tree.
 A min tree is a tree in which the key value in
each node is no larger than the key values in
its children. A min heap is a complete binary
tree that is also a min tree.
 Operations on heaps
– creation of an empty heap
– insertion of a new element into the heap;
– deletion of the largest element from the heap
*Figure 5.25: Sample max heaps (p.219)
[4]
14
12 7
8
10 6
9
6 3
5
30
25
[1]
[2] [3]
[5] [6]
[1]
[2] [3]
[4]
[1]
[2]
Property:
The root of max heap (min heap) contains
the largest (smallest).
2
7 4
8
10 6
10
20 83
50
11
21
[1]
[2] [3]
[5] [6]
[1]
[2] [3]
[4]
[1]
[2]
[4]
*Figure 5.26:Sample min heaps (p.220)
CHAPTER 5 50
ADT for Max Heap
structure MaxHeap
objects: a complete binary tree of n > 0 elements organized so that
the value in each node is at least as large as those in its children
functions:
for all heap belong to MaxHeap, item belong to Element, n,
max_size belong to integer
MaxHeap Create(max_size)::= create an empty heap that can
hold a maximum of max_size elements
Boolean HeapFull(heap, n)::= if (n==max_size) return TRUE
else return FALSE
MaxHeap Insert(heap, item, n)::= if (!HeapFull(heap,n)) insert
item into heap and return the resulting heap
else return error
Boolean HeapEmpty(heap, n)::= if (n>0) return FALSE
else return TRUE
Element Delete(heap,n)::= if (!HeapEmpty(heap,n)) return one
instance of the largest element in the heap
and remove it from the heap
else return error
CHAPTER 5 51
Application: priority queue
 machine service
– amount of time (min heap)
– amount of payment (max heap)
 factory
– time tag
CHAPTER 5 52
Data Structures
 unordered linked list
 unordered array
 sorted linked list
 sorted array
 heap
Representation Insertion Deletion
Unordered
array
(1) (n)
Unordered
linked list
(1) (n)
Sorted array O(n) (1)
Sorted linked
list
O(n) (1)
Max heap O(log2n) O(log2n)
*Figure 5.27: Priority queue representations (p.221)
CHAPTER 5 54
Example of Insertion to Max Heap
20
15 2
14 10
initial location of new node
21
15 20
14 10 2
insert 21 into heap
20
15 5
14 10 2
insert 5 into heap
CHAPTER 5 55
Insertion into a Max Heap
void insert_max_heap(element item, int *n)
{
int i;
if (HEAP_FULL(*n)) {
fprintf(stderr, “the heap is full.n”);
exit(1);
}
i = ++(*n);
while ((i!=1)&&(item.key>heap[i/2].key)) {
heap[i] = heap[i/2];
i /= 2;
}
heap[i]= item;
}
2k
-1=n ==> k=log2(n+1)
O(log2n)
CHAPTER 5 56
Example of Deletion from Max Heap
20
remove
15 2
14 10
10
15 2
14
15
14 2
10
CHAPTER 5 57
Deletion from a Max Heap
element delete_max_heap(int *n)
{
int parent, child;
element item, temp;
if (HEAP_EMPTY(*n)) {
fprintf(stderr, “The heap is emptyn”);
exit(1);
}
/* save value of the element with the
highest key */
item = heap[1];
/* use last element in heap to adjust heap
temp = heap[(*n)--];
parent = 1;
child = 2;
CHAPTER 5 58
while (child <= *n) {
/* find the larger child of the current
parent */
if ((child < *n)&&
(heap[child].key<heap[child+1].key))
child++;
if (temp.key >= heap[child].key) break;
/* move to the next lower level */
heap[parent] = heap[child];
child *= 2;
}
heap[parent] = temp;
return item;
}
CHAPTER 5 59
Binary Search Tree
 Heap
– a min (max) element is deleted. O(log2n)
– deletion of an arbitrary element O(n)
– search for an arbitrary element O(n)
 Binary search tree
– Every element has a unique key.
– The keys in a nonempty left subtree (right subtree) are
smaller (larger) than the key in the root of subtree.
– The left and right subtrees are also binary search trees.
CHAPTER 5 60
Examples of Binary Search Trees
20
12 25
10 15
30
5 40
2
60
70
65 80
22
CHAPTER 5 61
Searching a Binary Search Tree
tree_pointer search(tree_pointer root,
int key)
{
/* return a pointer to the node that
contains key. If there is no such
node, return NULL */
if (!root) return NULL;
if (key == root->data) return root;
if (key < root->data)
return search(root->left_child,
key);
return search(root->right_child,key);
}
CHAPTER 5 62
Another Searching Algorithm
tree_pointer search2(tree_pointer tree,
int key)
{
while (tree) {
if (key == tree->data) return tree;
if (key < tree->data)
tree = tree->left_child;
else tree = tree->right_child;
}
return NULL;
}
O(h)
CHAPTER 5 63
Insert Node in Binary Search Tree
30
5 40
2
30
5 40
2 35 80
30
5 40
2 80
Insert 80 Insert 35
CHAPTER 5 64
Insertion into A Binary Search Tree
void insert_node(tree_pointer *node, int num)
{tree_pointer ptr,
temp = modified_search(*node, num);
if (temp || !(*node)) {
ptr = (tree_pointer) malloc(sizeof(node));
if (IS_FULL(ptr)) {
fprintf(stderr, “The memory is fulln”);
exit(1);
}
ptr->data = num;
ptr->left_child = ptr->right_child = NULL;
if (*node)
if (num<temp->data) temp->left_child=ptr;
else temp->right_child = ptr;
else *node = ptr;
}
}
CHAPTER 5 65
Deletion for A Binary Search Tree
leaf
node
30
5
2
80
2
T1
T2
1
X
T2
1
T1
CHAPTER 5 66
Deletion for A Binary Search Tree
40
20 60
10 30 50 70
45 55
52
40
20 55
10 30 50 70
45 52
Before deleting 60 After deleting 60
non-leaf
node
CHAPTER 5 67
1
2
T1
T2 T3
1
2‘
T1
T2’ T3
CHAPTER 5 68
Selection Trees
(1) winner tree
(2) loser tree
CHAPTER 5 69
winner tree
6
6 8
9 6 8 17
8 9 90 17
20 6
10 9
15
16
20
38
20
30
15
25
15
50
11
16
100
110
18
20
run 1 run 2 run 3 run 4 run 5 run 6 run 7 run 8
ordered
sequence
sequential
allocation
scheme
(complete
binary
tree)
Each node represents
the smaller of its two
children.
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
*Figure 5.35: Selection tree of Figure 5.34 after one record has been
output and the tree restructured(nodes that were changed are ticked)
15
16
20
30
15
50
25
25
20
38
11
16
100
110
18
20
10
8
9
9
20
10
15
11
8
12
9
13
90
14
17
15
9
4
15
5 
8
6
17
7
9
2 
8
3
8
1 
CHAPTER 5 71
Analysis
 K: # of runs
 n: # of records
 setup time: O(K) (K-1)
 restructure time: O(log2K) log2(K+1)
 merge time: O(nlog2K)
 slight modification: tree of loser
– consider the parent node only (vs. sibling nodes)
10
8
9
9
20
10
6
11
8
12
9
13
90
14
17
15
10
4
20
5
9
6
90
7
9
2
17
3
8
1
6
Run 1 2 3 4 5 6 7 8
overall
winner
*Figure 5.36: Tree of losers corresponding to Figure 5.34 (p.235)
15
15
9
8
15
15
9
CHAPTER 5 73
Forest
 A forest is a set of n >= 0 disjoint trees
A E G
B C D F H I G
H
I
A
B
C
D
F
E
Forest
CHAPTER 5 74
Transform a forest into a binary tree
 T1, T2, …, Tn: a forest of trees
B(T1, T2, …, Tn): a binary tree
corresponding to this forest
 algorithm
(1) empty, if n = 0
(2) has root equal to root(T1)
has left subtree equal to B(T11,T12,…,T1m)
has right subtree equal to B(T2,T3,…,Tn)
CHAPTER 5 75
Forest Traversals
 Preorder
– If F is empty, then return
– Visit the root of the first tree of F
– Taverse the subtrees of the first tree in tree preorder
– Traverse the remaining trees of F in preorder
 Inorder
– If F is empty, then return
– Traverse the subtrees of the first tree in tree inorder
– Visit the root of the first tree
– Traverse the remaining trees of F is indorer
CHAPTER 5 76
D
H
A
B
F G
C
E
I
J
inorder: EFBGCHIJDA
preorder: ABEFCGDHIJ
A
B C D
E F
G H I J
B
E
F
C
G
D
H
I
J
preorde
r
CHAPTER 5 77
Set Representation
 S1={0, 6, 7, 8}, S2={1, 4, 9}, S3={2, 3, 5}
 Two operations considered here
– Disjoint set union S1  S2={0,6,7,8,1,4,9}
– Find(i): Find the set containing the element i.
3  S3, 8  S1
0
6 7 8
1
4 9
2
3 5
Si  Sj = 
CHAPTER 5 78
Disjoint Set Union
1
4 9
0
6 7 8
1
4 9
0
6 7 8
Possible representation for S1 union S2
Make one of trees a subtree of the other
0
6 7 8
4
1 9
2
3 5
set
name
pointer
S1
S2
S3
*Figure 5.41:Data Representation of S1S2and S3 (p.240)
CHAPTER 5 80
Array Representation for Set
int find1(int i)
{
for (; parent[i]>=0; i=parent[i])
return i;
}
void union1(int i, int j)
{
parent[i]= j;
}
i [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
parent -1 4 -1 2 -1 2 0 0 0 4
n-1
n-2
0



*Figure 5.43:Degenerate tree (p.242)
union operation
O(n) n-1
find operation
O(n2
)
i
i
n


2
union(0,1), find(0)
union(1,2), find(0)
.
.
.
union(n-2,n-1),find(0)
degenerate tree
*Figure 5.44:Trees obtained using the weighting rule(p.243)
weighting rule for union(i,j): if # of nodes in i < # in j then j the parent of i
CHAPTER 5 83
Modified Union Operation
void union2(int i, int j)
{
int temp = parent[i]+parent[j];
if (parent[i]>parent[j]) {
parent[i]=j;
parent[j]=temp;
}
else {
parent[j]=i;
parent[i]=temp;
}
}
If the number of nodes in tree i is
less than the number in tree j, then
make j the parent of i; otherwise
make i the parent of j.
Keep a count in the root of tree
i has fewer nodes.
j has fewer nodes
Figure 5.45:Trees achieving worst case bound (p.245)
 log28+1
CHAPTER 5 85
Modified Find(i) Operation
int find2(int i)
{
int root, trail, lead;
for (root=i; parent[root]>=0;
root=parent[root]);
for (trail=i; trail!=root;
trail=lead) {
lead = parent[trail];
parent[trail]= root;
}
return root:
}
If j is a node on the path from
i to its root then make j a child
of the root
CHAPTER 5 86
0
1 2 4
3 5 6
7
0
1 2 4
3 5
6 7
find(7) find(7) find(7) find(7) find(7) find(7) find(7) find(7)
go up 3 1 1 1 1 1 1 1
reset 2
12 moves (vs. 24 moves)
CHAPTER 5 87
Applications
 Find equivalence class i  j
 Find Si and Sj such that i  Si and j  Sj
(two finds)
– Si = Sj do nothing
– Si  Sj union(Si , Sj)
 example
0  4, 3  1, 6  10, 8  9, 7  4, 6  8,
3  5, 2  11, 11  0
{0, 2, 4, 7, 11}, {1, 3, 5}, {6, 8, 9, 10}
CHAPTER 5 88
preorder: A B C D E F G H I
inorder: B C A E D G H F I
A
B, C D, E, F, G, H, I
A
D, E, F, G, H, I
B
C
A
B
C
D
E F
G I
H
CHAPTER 6 89
CHAPTER 6
GRAPHS
All the programs in this file are selected from
Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed
“Fundamentals of Data Structures in C”,
Computer Science Press, 1992.
CHAPTER 6 90
Definition
 A graph G consists of two sets
– a finite, nonempty set of vertices V(G)
– a finite, possible empty set of edges E(G)
– G(V,E) represents a graph
 An undirected graph is one in which the pair of
vertices in a edge is unordered, (v0, v1) = (v1,v0)
 A directed graph is one in which each edge is a
directed pair of vertices, <v0, v1> != <v1,v0>
tail head
CHAPTER 6 91
Examples for Graph
0
1 2
3
0
1
2
0
1 2
3 4 5 6
G1
G2
G3
V(G1)={0,1,2,3} E(G1)={(0,1),(0,2),(0,3),(1,2),(1,3),(2,3)}
V(G2)={0,1,2,3,4,5,6} E(G2)={(0,1),(0,2),(1,3),(1,4),(2,5),(2,6)}
V(G3)={0,1,2} E(G3)={<0,1>,<1,0>,<1,2>}
complete undirected graph: n(n-1)/2 edges
complete directed graph: n(n-1) edges
complete graph incomplete graph
CHAPTER 6 92
Complete Graph
 A complete graph is a graph that has the
maximum number of edges
– for undirected graph with n vertices, the maximum
number of edges is n(n-1)/2
– for directed graph with n vertices, the maximum
number of edges is n(n-1)
– example: G1 is a complete graph
CHAPTER 6 93
Adjacent and Incident
 If (v0, v1) is an edge in an undirected graph,
– v0 and v1 are adjacent
– The edge (v0, v1) is incident on vertices v0 and v1
 If <v0, v1> is an edge in a directed graph
– v0 is adjacent to v1, and v1 is adjacent from v0
– The edge <v0, v1> is incident on v0 and v1
CHAPTER 6 94
0 2
1
(a)
2
1
0
3
(b)
*Figure 6.3:Example of a graph with feedback loops and a
multigraph (p.260)
self edge multigraph:
multiple occurrences
of the same edge
Figure 6.3
CHAPTER 6 95
 A subgraph of G is a graph G’ such that V(G’)
is a subset of V(G) and E(G’) is a subset of
E(G)
 A path from vertex vp to vertex vq in a graph G,
is a sequence of vertices, vp, vi1, vi2, ..., vin, vq,
such that (vp, vi1), (vi1, vi2), ..., (vin, vq) are edges
in an undirected graph
 The length of a path is the number of edges on
it
Subgraph and Path
CHAPTER 6 96
0 0
1 2 3
1 2 0
1 2
3
(i) (ii) (iii) (iv)
(a) Some of the subgraph of G1
0 0
1
0
1
2
0
1
2
(i) (ii) (iii) (iv)
(b) Some of the subgraph of G3
分開
單一
0
1 2
3
G1
0
1
2
G3
Figure 6.4: subgraphs of G1 and G3 (p.261)
CHAPTER 6 97
 A simple path is a path in which all vertices,
except possibly the first and the last, are distinct
 A cycle is a simple path in which the first and
the last vertices are the same
 In an undirected graph G, two vertices, v0 and v1,
are connected if there is a path in G from v0 to v1
 An undirected graph is connected if, for every
pair of distinct vertices vi, vj, there is a path
from vi to vj
Simple Path and Style
CHAPTER 6 98
0
1 2
3
0
1 2
3 4 5 6
G1
G2
connected
tree (acyclic graph)
CHAPTER 6 99
 A connected component of an undirected graph
is a maximal connected subgraph.
 A tree is a graph that is connected and acyclic.
 A directed graph is strongly connected if there
is a directed path from vi to vj and also
from vj to vi.
 A strongly connected component is a maximal
subgraph that is strongly connected.
Connected Component
CHAPTER 6 100
*Figure 6.5: A graph with two connected components (p.262)
1
0
2
3
4
5
6
7
H1
H2
G4 (not connected)
connected component (maximal connected subgraph)
CHAPTER 6 101
*Figure 6.6: Strongly connected components of G3 (p.262)
0
1
2
0
1
2
G3
not strongly connected
strongly connected component
(maximal strongly connected subgraph)
CHAPTER 6 102
Degree
 The degree of a vertex is the number of edges
incident to that vertex
 For directed graph,
– the in-degree of a vertex v is the number of edges
that have v as the head
– the out-degree of a vertex v is the number of edges
that have v as the tail
– if di is the degree of a vertex i in a graph G with n
vertices and e edges, the number of edges is
e di
n



( ) /
0
1
2
CHAPTER 6 103
undirected graph
degree
0
1 2
3 4 5 6
G1 G2
3
2
3 3
1 1 1 1
directed graph
in-degree
out-degree
0
1
2
G3
in:1, out: 1
in: 1, out: 2
in: 1, out: 0
0
1 2
3
3
3
3
CHAPTER 6 104
ADT for Graph
structure Graph is
objects: a nonempty set of vertices and a set of undirected edges, where each
edge is a pair of vertices
functions: for all graph  Graph, v, v1 and v2  Vertices
Graph Create()::=return an empty graph
Graph InsertVertex(graph, v)::= return a graph with v inserted. v has no
incident edge.
Graph InsertEdge(graph, v1,v2)::= return a graph with new edge
between v1 and v2
Graph DeleteVertex(graph, v)::= return a graph in which v and all edges
incident to it are removed
Graph DeleteEdge(graph, v1, v2)::=return a graph in which the edge (v1,
v2)
is removed
Boolean IsEmpty(graph)::= if (graph==empty graph) return TRUE
else return FALSE
List Adjacent(graph,v)::= return a list of all vertices that are adjacent to v
CHAPTER 6 105
Graph Representations
 Adjacency Matrix
 Adjacency Lists
 Adjacency Multilists
CHAPTER 6 106
Adjacency Matrix
 Let G=(V,E) be a graph with n vertices.
 The adjacency matrix of G is a two-dimensional
n by n array, say adj_mat
 If the edge (vi, vj) is in E(G), adj_mat[i][j]=1
 If there is no such edge in E(G), adj_mat[i][j]=0
 The adjacency matrix for an undirected graph is
symmetric; the adjacency matrix for a digraph
need not be symmetric
CHAPTER 6 107
Examples for Adjacency Matrix
0
1
1
1
1
0
1
1
1
1
0
1
1
1
1
0












0
1
0
1
0
0
0
1
0










0
1
1
0
0
0
0
0
1
0
0
1
0
0
0
0
1
0
0
1
0
0
0
0
0
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
1
0
1
0
0
0
0
0
0
1
0
1
0
0
0
0
0
0
1
0


























G1
G2
G4
0
1 2
3
0
1
2
1
0
2
3
4
5
6
7
symmetric
undirected: n2
/2
directed: n2
CHAPTER 6 108
Merits of Adjacency Matrix
 From the adjacency matrix, to determine the
connection of vertices is easy
 The degree of a vertex is
 For a digraph, the row sum is the out_degree,
while the column sum is the in_degree
adj mat i j
j
n
_ [ ][ ]



0
1
ind vi A j i
j
n
( ) [ , ]




0
1
outd vi A i j
j
n
( ) [ , ]




0
1
CHAPTER 6 109
Data Structures for Adjacency Lists
#define MAX_VERTICES 50
typedef struct node *node_pointer;
typedef struct node {
int vertex;
struct node *link;
};
node_pointer graph[MAX_VERTICES];
int n=0; /* vertices currently in use *
Each row in adjacency matrix is represented as an adjacency list.
CHAPTER 6 110
0
1
2
3
0
1
2
0
1
2
3
4
5
6
7
1 2 3
0 2 3
0 1 3
0 1 2
G1
1
0 2
G3
1 2
0 3
0 3
1 2
5
4 6
5 7
6
G4
0
1 2
3
0
1
2
1
0
2
3
4
5
6
7
An undirected graph with n vertices and e edges ==> n head nodes and 2e list nodes
CHAPTER 6 111
Interesting Operations
degree of a vertex in an undirected graph
–# of nodes in adjacency list
# of edges in a graph
–determined in O(n+e)
out-degree of a vertex in a directed graph
–# of nodes in its adjacency list
in-degree of a vertex in a directed graph
–traverse the whole data structure
CHAPTER 6 112
[0] 9 [8] 23 [16] 2
[1] 11 [9] 1 [17] 5
[2] 13 [10] 2 [18] 4
[3] 15 [11] 0 [19] 6
[4] 17 [12] 3 [20] 5
[5] 18 [13] 0 [21] 7
[6] 20 [14] 3 [22] 6
[7] 22 [15] 1
1
0
2
3
4
5
6
7
0
1
2
3
4
5
6
7
node[0] … node[n-1]: starting point for vertices
node[n]: n+2e+1
node[n+1] … node[n+2e]: head node of edge
Compact Representation
CHAPTER 6 113



0
1
2
1 NULL
0 NULL
1 NULL
0
1
2
Determine in-degree of a vertex in a fast way.
Figure 6.10: Inverse adjacency list for G3
CHAPTER 6 114
tail head column link for head row link for tail
Figure 6.11: Alternate node structure for adjacency lists (p.267)
CHAPTER 6 115
0 1 2
2 NULL
1
0
1 0NULL
0 1 NULL NULL
1 2 NULL NULL
0
1
2
0
1
0
1
0
0
0
1
0










Figure 6.12: Orthogonal representation for graph G3(p.268)
CHAPTER 6 116
 3  2 NULL
1 
0
 2  3 NULL
0 
1
 3  1 NULL
0 
2
 2  0 NULL
1 
3
headnodes vertax link
Order is of no significance.
0
1 2
3
Figure 6.13:Alternate order adjacency list for G1 (p.268)
CHAPTER 6 117
Adjacency Multilists
marked vertex1 vertex2 path1 path2
An edge in an undirected graph is
represented by two nodes in adjacency list
representation.
Adjacency Multilists
–lists in which nodes may be shared among
several lists.
(an edge is shared by two different paths)
CHAPTER 6 118
0 1 N2 N4
0 2 N3 N4
0 3 N5
1 2 N5 N6
1 3 N6
2 3
N1
N2
N3
N4
N5
N6
0
1
2
3
edge (0,1)
edge (0,2)
edge (0,3)
edge (1,2)
edge (1,3)
edge (2,3)
(1,0)
(2,0)
(3,0)
(2,1)
(3,1)
(3,2)
0
1 2
3
six edges
Lists: vertex 0: M1->M2->M3, vertex 1: M1->M4->M5
vertex 2: M2->M4->M6, vertex 3: M3->M5->M6
Example for Adjacency Multlists
CHAPTER 6 119
typedef struct edge *edge_pointer;
typedef struct edge {
short int marked;
int vertex1, vertex2;
edge_pointer path1, path2;
};
edge_pointer graph[MAX_VERTICES];
marked vertex1 vertex2 path1 path2
Adjacency Multilists
CHAPTER 6 120
Some Graph Operations
 Traversal
Given G=(V,E) and vertex v, find all wV,
such that w connects v.
– Depth First Search (DFS)
preorder tree traversal
– Breadth First Search (BFS)
level order tree traversal
 Connected Components
 Spanning Trees
CHAPTER 6 121
*Figure 6.19:Graph G and its adjacency lists (p.274)
depth first search: v0, v1, v3, v7, v4, v5, v2, v6
breadth first search: v0, v1, v2, v3, v4, v5, v6, v7
CHAPTER 6 122
Depth First Search
void dfs(int v)
{
node_pointer w;
visited[v]= TRUE;
printf(“%5d”, v);
for (w=graph[v]; w; w=w->link)
if (!visited[w->vertex])
dfs(w->vertex);
}
#define FALSE 0
#define TRUE 1
short int visited[MAX_VERTICES];
Data structure
adjacency list: O(e)
adjacency matrix: O(n2
)
CHAPTER 6 123
Breadth First Search
typedef struct queue *queue_pointer;
typedef struct queue {
int vertex;
queue_pointer link;
};
void addq(queue_pointer *,
queue_pointer *, int);
int deleteq(queue_pointer *);
CHAPTER 6 124
Breadth First Search (Continued)
void bfs(int v)
{
node_pointer w;
queue_pointer front, rear;
front = rear = NULL;
printf(“%5d”, v);
visited[v] = TRUE;
addq(&front, &rear, v);
adjacency list: O(e)
adjacency matrix: O(n2
)
CHAPTER 6 125
while (front) {
v= deleteq(&front);
for (w=graph[v]; w; w=w->link)
if (!visited[w->vertex]) {
printf(“%5d”, w->vertex);
addq(&front, &rear, w->vertex);
visited[w->vertex] = TRUE;
}
}
}
CHAPTER 6 126
Connected Components
void connected(void)
{
for (i=0; i<n; i++) {
if (!visited[i]) {
dfs(i);
printf(“n”);
}
}
}
adjacency list: O(n+e)
adjacency matrix: O(n2
)
CHAPTER 6 127
Spanning Trees
 When graph G is connected, a depth first or
breadth first search starting at any vertex will
visit all vertices in G
 A spanning tree is any tree that consists solely
of edges in G and that includes all the vertices
 E(G): T (tree edges) + N (nontree edges)
where T: set of edges used during search
N: set of remaining edges
CHAPTER 6 128
Examples of Spanning Tree
0
1 2
3
0
1 2
3
0
1 2
3
0
1 2
3
G1 Possible spanning trees
CHAPTER 6 129
Spanning Trees
 Either dfs or bfs can be used to create a
spanning tree
– When dfs is used, the resulting spanning tree is
known as a depth first spanning tree
– When bfs is used, the resulting spanning tree is
known as a breadth first spanning tree
 While adding a nontree edge into any spanning
tree, this will create a cycle
CHAPTER 6 130
DFS VS BFS Spanning Tree
0
1 2
3 4 5 6
7
0
1 2
3 4 5 6
7
DFS Spanning BFS Spanning
0
1 2
3 4 5 6
7 nontree edge
cycle
CHAPTER 6 131
A spanning tree is a minimal subgraph, G’, of G
such that V(G’)=V(G) and G’ is connected.
Any connected graph with n vertices must have
at least n-1 edges.
A biconnected graph is a connected graph that has
no articulation points. 0
1 2
3 4 5 6
7
biconnected graph
CHAPTER 6 132
1
3 5
6
0 8 9
7
2
4
connected graph
1
3 5
6
0 8 9
7
2
4
1
3 5
6
0 8 9
7
2
4
two connected components one connected graph
CHAPTER 6 133
biconnected component: a maximal connected subgraph H
(no subgraph that is both biconnected and properly contains H)
1
3 5
6
0 8 9
7
2
4
1
0
1
3
2
4
3 5
8
7
9
7
5
6
7
biconnected components
CHAPTER 6 134
Find biconnected component of a connected undirected graph
by depth first spanning tree
8 9
1
4 0
3
0 5
3 5
4 6
1 6
9 8 9 8
7 7
3
4 5
7
6
9 8
2
0
1
0
6
7
1 5
2
4
3
(a) depth first spanning tree (b)
2 2
dfn
depth
first
number
nontree
edge
(back edge)
nontree
edge
(back edge)
Why is cross edge impossible?
If u is an ancestor of v then dfn(u) < dfn(v).
CHAPTER 6 135
*Figure 6.24: dfn and low values for dfs spanning tree with root =3(p.281)
Vertax 0 1 2 3 4 5 6 7 8 9
dfn 4 3 2 0 1 5 6 7 9 8
low 4 0 0 0 0 5 5 5 9 8
CHAPTER 6 136
8 9
3
4 5
7
6
9 8
2
0
1
0
6
7
1 5
2
4
3
low(u)=min{dfn(u),
min{low(w)|w is a child of u},
min{dfn(w)|(u,w) is a back edge}
u: articulation point
low(child)  dfn(u)
*The root of a depth first spanning
tree is an articulation point iff
it has at least two children.
*Any other vertex u is an articulation
point iff it has at least one child w
such that we cannot reach an ancestor
of u using a path that consists of
(1) only w (2) descendants of w (3)
single back edge.
CHAPTER 6 137
8 9
3
4 5
7
6
9 8
2
0
1
6
7
1 5
2
4
3
vertex dfn low child low_child low:dfn
0 4 4 (4,n,n) null null null:4
1 3 0 (3,4,0) 0 4 4 3 
2 2 0 (2,0,n) 1 0 0 < 2
3 0 0 (0,0,n) 4,5 0,5 0,5 0 
4 1 0 (1,0,n) 2 0 0 < 1
5 5 5 (5,5,n) 6 5 5 5 
6 6 5 (6,5,n) 7 5 5 < 6
7 7 5 (7,8,5) 8,9 9,8 9,8 7 
8 9 9 (9,n,n) null null null, 9
9 8 8 (8,n,n) null null null, 8
CHAPTER 6 138
*Program 6.5: Initializaiton of dfn and low (p.282)
void init(void)
{
int i;
for (i = 0; i < n; i++) {
visited[i] = FALSE;
dfn[i] = low[i] = -1;
}
num = 0;
}
CHAPTER 6 139
*Program 6.4: Determining dfn and low (p.282)
Initial call: dfn(x,-1)
low[u]=min{dfn(u), …}
low[u]=min{…, min{low(w)|w is a child of u}, …}
low[u]=min{…,…,min{dfn(w)|(u,w) is a back edge}
dfn[w]0 非第一次,表示藉 back edge
v
u
w
v
u
X
O
void dfnlow(int u, int v)
{
/* compute dfn and low while performing a dfs search
beginning at vertex u, v is the parent of u (if any) */
node_pointer ptr;
int w;
dfn[u] = low[u] = num++;
for (ptr = graph[u]; ptr; ptr = ptr ->link) {
w = ptr ->vertex;
if (dfn[w] < 0) { /*w is an unvisited vertex */
dfnlow(w, u);
low[u] = MIN2(low[u], low[w]);
}
else if (w != v)
low[u] =MIN2(low[u], dfn[w] );
}
}
CHAPTER 6 140
*Program 6.6: Biconnected components of a graph (p.283)
low[u]=min{dfn(u), …}
(1) dfn[w]=-1 第一次
(2) dfn[w]!=-1 非第一次,藉 back
edge
void bicon(int u, int v)
{
/* compute dfn and low, and output the edges of G by their
biconnected components , v is the parent ( if any) of the u
(if any) in the resulting spanning tree. It is assumed that all
entries of dfn[ ] have been initialized to -1, num has been
initialized to 0, and the stack has been set to empty */
node_pointer ptr;
int w, x, y;
dfn[u] = low[u] = num ++;
for (ptr = graph[u]; ptr; ptr = ptr->link) {
w = ptr ->vertex;
if ( v != w && dfn[w] < dfn[u] )
add(&top, u, w); /* add edge to stack */
CHAPTER 6 141
if(dfn[w] < 0) {/* w has not been visited */
bicon(w, u);
low[u] = MIN2(low[u], low[w]);
if (low[w] >= dfn[u] ){ articulation point
printf(“New biconnected component: “);
do { /* delete edge from stack */
delete(&top, &x, &y);
printf(“ <%d, %d>” , x, y);
} while (!(( x = = u) && (y = = w)));
printf(“n”);
}
}
else if (w != v) low[u] = MIN2(low[u], dfn[w]);
}
}
low[u]=min{…, …, min{dfn(w)|(u,w) is a back edge}}
low[u]=min{…, min{low(w)|w is a child of u}, …
CHAPTER 6 142
Minimum Cost Spanning Tree
 The cost of a spanning tree of a weighted
undirected graph is the sum of the costs of the
edges in the spanning tree
 A minimum cost spanning tree is a spanning
tree of least cost
 Three different algorithms can be used
– Kruskal
– Prim
– Sollin
Select n-1 edges from a weighted graph
of n vertices with minimum cost.
CHAPTER 6 143
Greedy Strategy
 An optimal solution is constructed in stages
 At each stage, the best decision is made at this
time
 Since this decision cannot be changed later,
we make sure that the decision will result in a
feasible solution
 Typically, the selection of an item at each
stage is based on a least cost or a highest profit
criterion
CHAPTER 6 144
Kruskal’s Idea
 Build a minimum cost spanning tree T by
adding edges to T one at a time
 Select the edges for inclusion in T in
nondecreasing order of the cost
 An edge is added to T if it does not form a
cycle
 Since G is connected and has n > 0 vertices,
exactly n-1 edges will be selected
CHAPTER 6 145
Examples for Kruskal’s Algorithm
0
1
2
3
4
5 6
0
1
2
3
4
5 6
28
16
12
18
24
22
25
10
14
0
1
2
3
4
5 6
10
0 5
2 3
1 6
1 2
3 6
3 4
4 6
4 5
10
12
14
16
18
22
24
25
28
6/9
CHAPTER 6 146
0
1
2
3
4
5 6
10
12
0
1
2
3
4
5 6
10
12
14
0
1
2
3
4
5 6
10
12
14 16
0 5
2 3
1 6
1 2
3 6
3 4
4 6
4 5
0 1
10
12
14
16
18
22
24
25
28 + 3 6
cycle
CHAPTER 6 147
0 5
2 3
1 6
1 2
3 6
3 4
4 6
4 5
0 1
10
12
14
16
18
22
24
25
28
0
1
2
3
4
5 6
10
12
14 16
22
0
1
2
3
4
5 6
10
12
14 16
22
25
4 6
cycle
+
cost = 10 +25+22+12+16+14
CHAPTER 6 148
Kruskal’s Algorithm
T= {};
while (T contains less than n-1 edges
&& E is not empty) {
choose a least cost edge (v,w) from E;
delete (v,w) from E;
if ((v,w) does not create a cycle in T)
add (v,w) to T
else discard (v,w);
}
if (T contains fewer than n-1 edges)
printf(“No spanning treen”);
目標:取出 n-1 條 edges
min heap construction time O(e)
choose and delete O(log e)
find find & union O(log e)
{0,5}, {1,2,3,6}, {4} + edge(3,6) X + edge(3,4) --> {0,5},{1,2,3,4,6}
O(e log e)
CHAPTER 6 149
Prim’s Algorithm
T={};
TV={0};
while (T contains fewer than n-1 edges)
{
let (u,v) be a least cost edge such
that and
if (there is no such edge ) break;
add v to TV;
add (u,v) to T;
}
if (T contains fewer than n-1 edges)
printf(“No spanning treen”);
u TV
 v TV

(tree all the time vs. forest)
CHAPTER 6 150
Examples for Prim’s Algorithm
0
1
2
3
4
5 6
0
1
2
3
4
5 6
10
0
1
2
3
4
5 6
10
10
25 25
22
0
1
2
3
4
5 6
28
16
12
18
24
22
25
10
14
CHAPTER 6 151
0
1
2
3
4
5 6
10
25
22
12
0
1
2
3
4
5 6
10
25
22
12
16
0
1
2
3
4
5 6
10
25
22
12
16
14
0
1
2
3
4
5 6
28
16
12
18
24
22
25
10
14
CHAPTER 6 152
Sollin’s Algorithm
0
1
2
3
4
5 6
10
0
22
12
16
14
0
1
2
3
4
5 6
10
22
12
14
0
1
2
3
4
5 6
0
1
2
3
4
5 6
28
16
12
18
24
22
25
10
14
vertex edge
0 0 -- 10 --> 5, 0 -- 28 --> 1
1 1 -- 14 --> 6, 1-- 16 --> 2, 1 -- 28 --> 0
2 2 -- 12 --> 3, 2 -- 16 --> 1
3 3 -- 12 --> 2, 3 -- 18 --> 6, 3 -- 22 --> 4
4 4 -- 22 --> 3, 4 -- 24 --> 6, 5 -- 25 --> 5
5 5 -- 10 --> 0, 5 -- 25 --> 4
6 6 -- 14 --> 1, 6 -- 18 --> 3, 6 -- 24 --> 4
{0,5}
5 4 0 1
25 28
{1,6}
1 2
16 28
1
6 3 6 4
18 24
CHAPTER 6 153
*Figure 6.29: Graph and shortest paths from v0 (p.293)
V0 V4
V1
V5
V3
V2
50 10
20 10 15 20 35 30
15 3
45
(a)
path length
1) v0 v2 10
2) v0 v2 v3 25
3) v0 v2 v3 v1 45
4) v0 v4 45
(b)
Single Source All Destinations
Determine the shortest paths from v0 to all the remaining vertices.
CHAPTER 6 154
Example for the Shortest Path
0
1 2
3
4
5
6
7
San
Francisco
Denver
Chicago
Boston
New
York
Miami
New Orleans
Los Angeles
300 1000
800
1200
1500
1400
1000
900
1700
1000
250
0 1 2 3 4 5 6 7
0 0
1 300 0
2 1000 800 0
3 1200 0
4 1500 0 250
5 1000 0 900 1400
6 0 1000
7 1700 0
Cost adjacency matrix
CHAPTER 6 155
4
3
5
1500
250
4
3
5
1500
250
1000
選 5 4 到 3 由 1500 改成 1250
4
5
250
6
900
4 到 6 由改成 1250
4
5
250
7 1400
4 到 7 由改成 1650
4
5
250
6
900
7 1400
3
1000
選 6
4
5
250
6
900
7 1400
1000
4-5-6-7 比 4-5-7 長
(a) (b) (c)
(d) (e) (f)
CHAPTER 6 156
4
5
250
6
900
7 1400
3
1000
選 3
4
5
250
6
900
7 1400
3
1000
2
1200
4 到 2 由改成 2450
4
5
250
6
900
7 1400
3
1000
2
1200
選 7
4
5
250
7 1400
0
4 到 0 由改成 3350
(g) (h)
(i)
(j)
CHAPTER 6 157
Example for the Shortest Path
(Continued)
Iteration S Vertex
Selected
LA
[0]
SF
[1]
DEN
[2]
CHI
[3]
BO
[4]
NY
[5]
MIA
[6]
NO
Initial -- ---- + + + 1500 0 250 + +
1 {4} 5 + + + 1250 0 250 1150 1650
2 {4,5} 6 + + + 1250 0 250 1150 1650
3 {4,5,6} 3 + + 2450 1250 0 250 1150 1650
4 {4,5,6,3} 7 3350 + 2450 1250 0 250 1150 1650
5 {4,5,6,3,7} 2 3350 3250 2450 1250 0 250 1150 1650
6 {4,5,6,3,7,2} 1 3350 3250 2450 1250 0 250 1150 1650
7 {4,5,6,3,7,2,1}
(a)
(b) (c) (d)
(e)
(f)
(g)
(h)
(i)
(j)
CHAPTER 6 158
Data Structure for SSAD
#define MAX_VERTICES 6
int cost[][MAX_VERTICES]=
{{ 0, 50, 10, 1000, 45, 1000},
{1000, 0, 15, 1000, 10, 1000},
{ 20, 1000, 0, 15, 1000, 1000},
{1000, 20, 1000, 0, 35, 1000},
{1000, 1000, 30, 1000, 0, 1000},
{1000, 1000, 1000, 3, 1000, 0}};
int distance[MAX_VERTICES];
short int found{MAX_VERTICES];
int n = MAX_VERTICES;
adjacency matrix
CHAPTER 6 159
Single Source All Destinations
void shortestpath(int v, int cost[]
[MAX_ERXTICES], int distance[], int n, short
int found[])
{
int i, u, w;
for (i=0; i<n; i++) {
found[i] = FALSE;
distance[i] = cost[v][i];
}
found[v] = TRUE;
distance[v] = 0;
O(n)
CHAPTER 6 160
for (i=0; i<n-2; i++) {determine n-1 paths from v
u = choose(distance, n, found);
found[u] = TRUE;
for (w=0; w<n; w++)
if (!found[w])
if (distance[u]+cost[u][w]<distance[w])
distance[w] = distance[u]+cost[u][w];
}
}
O(n2
)
與 u 相連的端點 w
CHAPTER 6 161
All Pairs Shortest Paths
Find the shortest paths between all pairs of
vertices.
Solution 1
–Apply shortest path n times with each vertex as
source.
O(n3
)
Solution 2
–Represent the graph G by its cost adjacency matrix
with cost[i][j]
–If the edge <i,j> is not in G, the cost[i][j] is set to
some sufficiently large number
–A[i][j] is the cost of the shortest path form i to j,
using only those intermediate vertices with an index
<= k
CHAPTER 6 162
All Pairs Shortest Paths (Continued)
 The cost of the shortest path from i to j is A [i][j],
as no vertex in G has an index greater than n-1
 A [i][j]=cost[i][j]
 Calculate the A, A, A, ..., A from A iteratively
 A [i][j]=min{A [i][j], A [i][k]+A [k][j]}, k>=0
n-1
-1
0 1 2 n-1 -1
k k-1 k-1 k-1
CHAPTER 6 163
Graph with negative cycle
0 1 2
-2
1 1
(a) Directed graph (b) A-1














0
1
0
2
1
0
The length of the shortest path from vertex 0 to vertex 2 is -.
0, 1, 0, 1,0, 1, …, 0, 1, 2
CHAPTER 6 164
Algorithm for All Pairs Shortest Paths
void allcosts(int cost[][MAX_VERTICES],
int distance[][MAX_VERTICES], int n)
{
int i, j, k;
for (i=0; i<n; i++)
for (j=0; j<n; j++)
distance[i][j] = cost[i][j];
for (k=0; k<n; k++)
for (i=0; i<n; i++)
for (j=0; j<n; j++)
if (distance[i][k]+distance[k][j]
< distance[i][j])
distance[i][j]=
distance[i][k]+distance[k][j];
}
CHAPTER 6 165
* Figure 6.33: Directed graph and its cost matrix (p.299)
V0
V2
V1
6
4
3 11 2
(a)Digraph G (b)Cost adjacency matrix for G
0 1 2
0 0 4 11
1 6 0 2
2 3  0
CHAPTER 6 166
0 1 2
0 0 4 11
1 6 0 2
2 3  0
A-1
0 1 2
0 0 4 11
1 6 0 2
2 3 7 0
A0
0 1 2
0 0 4 6
1 6 0 2
2 3 7 0
A1
0 1 2
0 0 4 6
1 5 0 2
2 3 7 0
A2
V0
V2
V1
6
4
3 11 2
A-1
0 0
6 4
3 11
A0
4 6
0 0
7 2
A1
6 3
2 7
0 0
v0
v1 v2
CHAPTER 6 167
0 1 4
3
2
















0
0
1
0
0
1
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
1
0
















1
1
1
0
0
1
1
1
0
0
1
1
1
0
0
1
1
1
0
0
1
1
1
1
0
0
1
2
3
4
0
1
2
3
4 















1
1
1
0
0
1
1
1
0
0
1
1
1
0
0
1
1
1
1
0
1
1
1
1
1
0
1
2
3
4
(a) Digraph G (b) Adjacency matrix A for G
(c) transitive closure matrix A+
(d) reflexive transitive closure matrix A*
cycle
reflexiv
e
Transitive Closure
Goal: given a graph with unweighted edges, determine if there is a path
from i to j for all i and j.
(1) Require positive path (> 0) lengths.
(2) Require nonnegative path (0) lengths.
There is a path of length > 0 There is a path of length 0
transitive closure matrix
reflexive transitive closure matrix
CHAPTER 6 168
Activity on Vertex (AOV) Network
definition
A directed graph in which the vertices represent
tasks or activities and the edges represent
precedence relations between tasks.
predecessor (successor)
vertex i is a predecessor of vertex j iff there is a
directed path from i to j. j is a successor of i.
partial order
a precedence relation which is both transitive (i, j,
k, ij & jk => ik ) and irreflexive (x xx).
acylic graph
a directed graph with no directed cycles
CHAPTER 6 169
*Figure 6.38: An AOV network (p.305)
Topological order:
linear ordering of vertices
of a graph
i, j if i is a predecessor of
j, then i precedes j in the
linear ordering
C1, C2, C4, C5, C3, C6, C8,
C7, C10, C13, C12, C14, C15,
C11, C9
C4, C5, C2, C1, C6, C3, C8,
C15, C7, C9, C10, C11, C13,
C12, C14
CHAPTER 6 170
*Program 6.13: Topological sort (p.306)
for (i = 0; i <n; i++) {
if every vertex has a predecessor {
fprintf(stderr, “Network has a cycle. n “ );
exit(1);
}
pick a vertex v that has no predecessors;
output v;
delete v and all edges leading out of v
from the network;
}
CHAPTER 6 171
*Figure 6.39:Simulation of Program 6.13 on an AOV
network (p.306)
v0 no predecessor
delete v0->v1, v0->v2, v0->v3
v1, v2, v3 no predecessor
select v3
delete v3->v4, v3->v5
select v2
delete v2->v4, v2->v5
select v5 select v1
delete v1->v4
CHAPTER 6 172
Issues in Data Structure
Consideration
Decide whether a vertex has any predecessors.
–Each vertex has a count.
Decide a vertex together with all its incident
edges.
–Adjacency list
CHAPTER 6 173
*Figure 6.40:Adjacency list representation of Figure 6.30(a)
(p.309)
0  1  2  3 NULL
1  4 NULL
1  4  5 NULL
1  5  4 NULL
3 NULL
2 NULL
V0
V1
V2
V3
V4
V5
v0
v1
v2
v3
v4
v5
count link
headnodes
vertex link
node
CHAPTER 6 174
*(p.307)
typedef struct node *node_pointer;
typedef struct node {
int vertex;
node_pointer link;
};
typedef struct {
int count;
node_pointer link;
} hdnodes;
hdnodes graph[MAX_VERTICES];
CHAPTER 6 175
*Program 6.14: Topological sort (p.308)
O(n)
void topsort (hdnodes graph [] , int n)
{
int i, j, k, top;
node_pointer ptr;
/* create a stack of vertices with no predecessors */
top = -1;
for (i = 0; i < n; i++)
if (!graph[i].count) {no predecessors, stack is linked through
graph[i].count = top; count field
top = i;
}
for (i = 0; i < n; i++)
if (top == -1) {
fprintf(stderr, “n Network has a cycle. Sort terminated. n”);
exit(1);
}
CHAPTER 6 176
O(e)
O(e+n)
Continued
}
else {
j = top; /* unstack a vertex */
top = graph[top].count;
printf(“v%d, “, j);
for (ptr = graph [j]. link; ptr ;ptr = ptr ->link ){
/* decrease the count of the successor vertices of j */
k = ptr ->vertex;
graph[k].count --;
if (!graph[k].count) {
/* add vertex k to the stack*/
graph[k].count = top;
top = k;
}
}
}
}
CHAPTER 6 177
Activity on Edge (AOE)
Networks
directed edge
–tasks or activities to be performed
vertex
–events which signal the completion of certain activities
number
–time required to perform the activity
CHAPTER 6 178
*Figure 6.41:An AOE network(p.310)
concurrent
CHAPTER 6 179
Application of AOE Network
Evaluate performance
–minimum amount of time
–activity whose duration time should be shortened
–…
Critical path
–a path that has the longest length
–minimum time required to complete the project
–v0, v1, v4, v7, v8 or v0, v1, v4, v6, v8 (18)
CHAPTER 6 180
other factors
Earliest time that vi can occur
–the length of the longest path from v0 to vi
–the earliest start time for all activities leaving vi
–early(6) = early(7) = 7
Latest time of activity
–the latest time the activity may start without increasing
the project duration
–late(5)=8, late(7)=7
Critical activity
–an activity for which early(i)=late(i)
–early(7)=late(7)
late(i)-early(i)
–measure of how critical an activity is
–late(5)-early(5)=8-5=3
CHAPTER 6 181
v0
v1
v2
v3
v4
v5
v6
v7
v8
a0=6
a1=4
a2=5
a3=1
a4=1
a5=2
a6=9
a7=7
a9=2
a10=4
a8=4
earliest, early, latest, late
0
0
6
6
7
7
16
16
18
0
4
4 7
14
14
0
5
5
7
7
0
0
6
6
7
7
16
10
18
2
6
6
14
14
14
10
8
8
3
CHAPTER 6 182
Determine Critical Paths
Delete all noncritical activities
Generate all the paths from the start to
finish vertex.
CHAPTER 6 183
Calculation of Earliest Times
vk vl
ai
early(i)=earliest(k)
late(i)=latest(l)-duration of ai
earliest[0]=0
earliest[j]=max{earliest[i]+duration of <i,j>}
i p(j)
earliest[j]
–the earliest event occurrence time
latest[j]
–the latest event occurrence time
CHAPTER 6 184
vi1
vi2
vin
.
.
.
vj
forward stage
if (earliest[k] < earliest[j]+ptr->duration)
earliest[k]=earliest[j]+ptr->duration
CHAPTER 6 185
*Figure 6.42:Computing earliest from topological sort
(p.313)
v0
v1
v2
v3
v4
v6
v7
v8
v5
CHAPTER 6 186
Calculation of Latest Times
 latest[j]
– the latest event occurrence time
latest[n-1]=earliest[n-1]
latest[j]=min{latest[i]-duration of <j,i>}
i s(j)
vi1
vi2
vin
.
.
.
vj backward stage
if (latest[k] > latest[j]-ptr->duration)
latest[k]=latest[j]-ptr->duration
CHAPTER 6 187
*Figure 6.43: Computing latest for AOE network of Figure 6.41(a)(p.314)
CHAPTER 6 188
*Figure 6.43(continued):Computing latest of AOE network of Figure 6.41(a)
(p.315)
latest[8]=earliest[8]=18
latest[6]=min{earliest[8] - 2}=16
latest[7]=min{earliest[8] - 4}=14
latest[4]=min{earliest[6] - 9;earliest[7] -7}= 7
latest[1]=min{earliest[4] - 1}=6
latest[2]=min{earliest[4] - 1}=6
latest[5]=min{earliest[7] - 4}=10
latest[3]=min{earliest[5] - 2}=8
latest[0]=min{earliest[1] - 6;earliest[2]- 4; earliest[3] -
5}=0
(c)Computation of latest from Equation (6.4) using a reverse topological
order
CHAPTER 6 189
*Figure 6.44:Early, late and critical values(p.316)
Activity Early Late Late-
Early
Critical
a0
a1
a2
a3
a4
a5
a6
a7
a8
a9
a10
0
0
0
6
4
5
7
7
7
16
14
0
2
3
6
6
8
7
7
10
16
14
0
2
3
0
2
3
0
0
3
0
0
Yes
No
No
Yes
No
No
Yes
Yes
No
Yes
Yes
CHAPTER 6 190
*Figure 6.45:Graph with noncritical activities deleted
(p.316)
V0
V4
V8
V1
V6
V7
a0
a3 a6
a7
a10
a9
CHAPTER 6 191
*Figure 6.46: AOE network with unreachable activities (p.317)
V0
V3
V1
V5
V2
V4
a0
a1
a2
a3
a5
a6
a4
earliest[i]=0
CHAPTER 6 192
*Figure 6.47: an AOE network(p.317)
V5 V8 V9
a10=5 a13=2
V2 V4 V7
a4=3 a9=4
V1 V3 V6
a2=3 a6=4
V0
a12=4
a11=2
a8=1
a7=4
a5=3
a3=6
a0=5
a1=6
start
finish

More Related Content

PPT
chapter5.PPT
PPT
Unit 3 Tree chapter 5
PPT
Admissions in india 2015
PPT
Lecture 5 tree.pptx
PPTX
PPT
358 33 powerpoint-slides_10-trees_chapter-10
PPTX
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
PPTX
Binary Trees.pptx module 122img 787554yau
chapter5.PPT
Unit 3 Tree chapter 5
Admissions in india 2015
Lecture 5 tree.pptx
358 33 powerpoint-slides_10-trees_chapter-10
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
Binary Trees.pptx module 122img 787554yau

Similar to Trees Traversals Expressions in Data structures.ppt (20)

PPT
Chap 5 Tree.ppt
PPTX
Lecture 8 data structures and algorithms
PPT
data_structures_and_applications_-_module-4.ppt
PPT
Data Structure And Algorithms for Computer Science
PPT
PDF
Chapter 5_Trees.pdf
PPT
Data Structures 4
PPT
ds 10-Binary Tree.ppt
PPTX
non linear data structure -introduction of tree
PPTX
Introduction to Tree_Data Structure.pptx
PPTX
Unit 6 tree
PPTX
Tree.pptx
PPTX
BASIC TREE AND TYPES OF DI CONCEPTS.pptx
PPT
Unit8 C
PPTX
Data structure using c module 2
PPTX
NON-LINEAR DATA STRUCTURE-TREES.pptx
PDF
Tree terminology and introduction to binary tree
PPT
Data Structure and Algorithms Binary Tree
PPTX
Unit-VStackStackStackStackStackStack.pptx
Chap 5 Tree.ppt
Lecture 8 data structures and algorithms
data_structures_and_applications_-_module-4.ppt
Data Structure And Algorithms for Computer Science
Chapter 5_Trees.pdf
Data Structures 4
ds 10-Binary Tree.ppt
non linear data structure -introduction of tree
Introduction to Tree_Data Structure.pptx
Unit 6 tree
Tree.pptx
BASIC TREE AND TYPES OF DI CONCEPTS.pptx
Unit8 C
Data structure using c module 2
NON-LINEAR DATA STRUCTURE-TREES.pptx
Tree terminology and introduction to binary tree
Data Structure and Algorithms Binary Tree
Unit-VStackStackStackStackStackStack.pptx
Ad

More from Vivekananda Gn (20)

PPTX
Stream Ciphers and Block Ciphers in Security.pptx
PPTX
Introduction to Network and Information Security.pptx
PPT
Network and Information Security unit2.ppt.ppt
PPT
Network and Information Security unit 1.ppt
PPT
Sorting and Searching in Data Structures.ppt
PPT
STACKS AND QUEUES in Data Structures.ppt
PPT
Introduction to Data structures and Trees.ppt
PPTX
Virtualization concepts in Operating systems.pptx
PPTX
Unix Commands and Shells Scripts in OS.pptx
PPTX
Security and Protection in operating systems.pptx
PPTX
Concurrency and Inter-Process communication.pptx
PPTX
Unix-Linux Operating Systems and its concepts
PPTX
Network-Administration-ITA3011 BCA VIT Vellore
PPTX
project Idea on Online food ordering system
PPT
Software Architecture and Design Details Module
PPT
memory allocation techniques in operating systems
PPT
virtual memory concepts in operating systems
PPTX
user authentication in cryptography and network security.pptx
PPTX
vector processing, pipelining - computer organization.pptx
PPTX
OS Building and Booting in Fundamentals of OS
Stream Ciphers and Block Ciphers in Security.pptx
Introduction to Network and Information Security.pptx
Network and Information Security unit2.ppt.ppt
Network and Information Security unit 1.ppt
Sorting and Searching in Data Structures.ppt
STACKS AND QUEUES in Data Structures.ppt
Introduction to Data structures and Trees.ppt
Virtualization concepts in Operating systems.pptx
Unix Commands and Shells Scripts in OS.pptx
Security and Protection in operating systems.pptx
Concurrency and Inter-Process communication.pptx
Unix-Linux Operating Systems and its concepts
Network-Administration-ITA3011 BCA VIT Vellore
project Idea on Online food ordering system
Software Architecture and Design Details Module
memory allocation techniques in operating systems
virtual memory concepts in operating systems
user authentication in cryptography and network security.pptx
vector processing, pipelining - computer organization.pptx
OS Building and Booting in Fundamentals of OS
Ad

Recently uploaded (20)

PPT
Mechanical Engineering MATERIALS Selection
PDF
Well-logging-methods_new................
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
UNIT 4 Total Quality Management .pptx
PPT
introduction to datamining and warehousing
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
Lecture Notes Electrical Wiring System Components
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
web development for engineering and engineering
PPTX
Current and future trends in Computer Vision.pptx
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Geodesy 1.pptx...............................................
Mechanical Engineering MATERIALS Selection
Well-logging-methods_new................
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Foundation to blockchain - A guide to Blockchain Tech
UNIT 4 Total Quality Management .pptx
introduction to datamining and warehousing
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Lecture Notes Electrical Wiring System Components
Automation-in-Manufacturing-Chapter-Introduction.pdf
bas. eng. economics group 4 presentation 1.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Model Code of Practice - Construction Work - 21102022 .pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
web development for engineering and engineering
Current and future trends in Computer Vision.pptx
CYBER-CRIMES AND SECURITY A guide to understanding
Geodesy 1.pptx...............................................

Trees Traversals Expressions in Data structures.ppt

  • 1. UNIT 3 Trees All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals of Data Structures in C”, Computer Science Press, 1992.
  • 2. CHAPTER 5 2 Trees Gill Tansey Brunhilde Tweed Zoe Terry Honey Bear Crocus Primrose Coyote Nous Belle Nugget Brandy Dusty Root leaf
  • 3. CHAPTER 5 3 Definition of Tree  A tree is a finite set of one or more nodes such that:  There is a specially designated node called the root.  The remaining nodes are partitioned into n>=0 disjoint sets T1, ..., Tn, where each of these sets is a tree.  We call T1, ..., Tn the subtrees of the root.
  • 4. CHAPTER 5 4 Level and Depth K L E F B G C M H I J D A Level 1 2 3 4 node (13) degree of a node leaf (terminal) nonterminal parent children sibling degree of a tree (3) ancestor level of a node height of a tree (4) 3 2 1 3 2 0 0 1 0 0 0 0 0 1 2 2 2 3 3 3 3 3 3 4 4 4
  • 5. CHAPTER 5 5 Terminology  The degree of a node is the number of subtrees of the node – The degree of A is 3; the degree of C is 1.  The node with degree 0 is a leaf or terminal node.  A node that has subtrees is the parent of the roots of the subtrees.  The roots of these subtrees are the children of the node.  Children of the same parent are siblings.  The ancestors of a node are all the nodes along the path from the root to the node.
  • 6. CHAPTER 5 6 Representation of Trees  List Representation – ( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) ) – The root comes first, followed by a list of sub-trees data link 1 link 2 ... link n How many link fields are needed in such a representation?
  • 7. CHAPTER 5 7 Left Child - Right Sibling A B C D E F G H I J K L M data left child right sibling
  • 8. CHAPTER 5 8 Binary Trees  A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree.  Any tree can be transformed into binary tree. – by left child-right sibling representation  The left subtree and the right subtree are distinguished.
  • 9. J I M H L A B C D E F G K *Figure 5.6: Left child-right child tree representation of a tree (p.191)
  • 10. CHAPTER 5 10 Abstract Data Type Binary_Tree structure Binary_Tree(abbreviated BinTree) is objects: a finite set of nodes either empty or consisting of a root node, left Binary_Tree, and right Binary_Tree. functions: for all bt, bt1, bt2  BinTree, item  element Bintree Create()::= creates an empty binary tree Boolean IsEmpty(bt)::= if (bt==empty binary tree) return TRUE else return FALSE
  • 11. CHAPTER 5 11 BinTree MakeBT(bt1, item, bt2)::= return a binary tree whose left subtree is bt1, whose right subtree is bt2, and whose root node contains the data item Bintree Lchild(bt)::= if (IsEmpty(bt)) return error else return the left subtree of bt element Data(bt)::= if (IsEmpty(bt)) return error else return the data in the root node of bt Bintree Rchild(bt)::= if (IsEmpty(bt)) return error else return the right subtree of bt
  • 12. CHAPTER 5 12 Samples of Trees A B A B A B C G E I D H F Complete Binary Tree Skewed Binary Tree E C D 1 2 3 4 5
  • 13. CHAPTER 5 13 Maximum Number of Nodes in BT  The maximum number of nodes on level i of a binary tree is 2i-1 , i>=1.  The maximum nubmer of nodes in a binary tree of depth k is 2k -1, k>=1. i-1 Prove by induction. 2 2 1 1 1 i i k k     
  • 14. CHAPTER 5 14 Relations between Number of Leaf Nodes and Nodes of Degree 2 For any nonempty binary tree, T, if n0 is the number of leaf nodes and n2 the number of nodes of degree 2, then n0=n2+1 proof: Let n and B denote the total number of nodes & branches in T. Let n0, n1, n2 represent the nodes with no children single child, and two children respectively. n= n0+n1+n2, B+1=n, B=n1+2n2 ==> n1+2n2+1= n n1+2n2+1= n0+n1+n2 ==> n0=n2+1
  • 15. CHAPTER 5 15 Full BT VS Complete BT  A full binary tree of depth k is a binary tree of depth k having 2 -1 nodes, k>=0.  A binary tree with n nodes and depth k is complete iff its nodes correspond to the nodes numbered from 1 to n in the full binary tree of depth k. k A B C G E I D H F A B C G E K D J F I H O N M L 由上至下, 由左至右編號 Full binary tree of depth 4 Complete binary tree
  • 16. CHAPTER 5 16 Binary Tree Representations  If a complete binary tree with n nodes (depth = log n + 1) is represented sequentially, then for any node with index i, 1<=i<=n, we have: – parent(i) is at i/2 if i!=1. If i=1, i is at the root and has no parent. – left_child(i) ia at 2i if 2i<=n. If 2i>n, then i has no left child. – right_child(i) ia at 2i+1 if 2i +1 <=n. If 2i +1 >n, then i has no right child.
  • 17. CHAPTER 5 17 Sequential Representation A B -- C -- -- -- D -- . E [1] [2] [3] [4] [5] [6] [7] [8] [9] . [16] [1] [2] [3] [4] [5] [6] [7] [8] [9] A B C D E F G H I A B E C D A B C G E I D H F (1) waste space (2) insertion/deletion problem
  • 18. CHAPTER 5 18 Linked Representation typedef struct node *tree_pointer; typedef struct node { int data; tree_pointer left_child, right_child; }; data left_child right_child data left_child right_child
  • 19. CHAPTER 5 19 Binary Tree Traversals  Let L, V, and R stand for moving left, visiting the node, and moving right.  There are six possible combinations of traversal – LVR, LRV, VLR, VRL, RVL, RLV  Adopt convention that we traverse left before right, only 3 traversals remain – LVR, LRV, VLR – inorder, postorder, preorder
  • 20. CHAPTER 5 20 Arithmetic Expression Using BT + * A * / E D C B inorder traversal A / B * C * D + E infix expression preorder traversal + * * / A B C D E prefix expression postorder traversal A B / C * D * E + postfix expression level order traversal + * E * D / C A B
  • 21. CHAPTER 5 21 Inorder Traversal (recursive version) void inorder(tree_pointer ptr) /* inorder tree traversal */ { if (ptr) { inorder(ptr->left_child); printf(“%d”, ptr->data); indorder(ptr->right_child); } } A / B * C * D + E
  • 22. CHAPTER 5 22 Preorder Traversal(recursive version) void preorder(tree_pointer ptr) /* preorder tree traversal */ { if (ptr) { printf(“%d”, ptr->data); preorder(ptr->left_child); predorder(ptr->right_child); } } + * * / A B C D E
  • 23. CHAPTER 5 23 Postorder Traversal (recursive version) void postorder(tree_pointer ptr) /* postorder tree traversal */ { if (ptr) { postorder(ptr->left_child); postdorder(ptr->right_child); printf(“%d”, ptr->data); } } A B / C * D * E +
  • 24. CHAPTER 5 24 Iterative Inorder Traversal (using stack) void iter_inorder(tree_pointer node) { int top= -1; /* initialize stack */ tree_pointer stack[MAX_STACK_SIZE]; for (;;) { for (; node; node=node->left_child) add(&top, node);/* add to stack */ node= delete(&top); /* delete from stack */ if (!node) break; /* empty stack */ printf(“%D”, node->data); node = node->right_child; } } O(n)
  • 25. CHAPTER 5 25 Trace Operations of Inorder Traversal Call of inorder Value in root Action Call of inorder Value in root Action 1 + 11 C 2 * 12 NULL 3 * 11 C printf 4 / 13 NULL 5 A 2 * printf 6 NULL 14 D 5 A printf 15 NULL 7 NULL 14 D printf 4 / printf 16 NULL 8 B 1 + printf 9 NULL 17 E 8 B printf 18 NULL 10 NULL 17 E printf 3 * printf 19 NULL
  • 26. CHAPTER 5 26 Level Order Traversal (using queue) void level_order(tree_pointer ptr) /* level order tree traversal */ { int front = rear = 0; tree_pointer queue[MAX_QUEUE_SIZE]; if (!ptr) return; /* empty queue */ addq(front, &rear, ptr); for (;;) { ptr = deleteq(&front, rear);
  • 27. CHAPTER 5 27 if (ptr) { printf(“%d”, ptr->data); if (ptr->left_child) addq(front, &rear, ptr->left_child); if (ptr->right_child) addq(front, &rear, ptr->right_child); } else break; } } + * E * D / C A B
  • 28. CHAPTER 5 28 Copying Binary Trees tree_poointer copy(tree_pointer original) { tree_pointer temp; if (original) { temp=(tree_pointer) malloc(sizeof(node)); if (IS_FULL(temp)) { fprintf(stderr, “the memory is fulln”); exit(1); } temp->left_child=copy(original->left_child); temp->right_child=copy(original->right_child) temp->data=original->data; return temp; } return NULL; } postorder
  • 29. CHAPTER 5 29 Equality of Binary Trees int equal(tree_pointer first, tree_pointer second) { /* function returns FALSE if the binary trees first and second are not equal, otherwise it returns TRUE */ return ((!first && !second) || (first && second && (first->data == second->data) && equal(first->left_child, second->left_child) && equal(first->right_child, second->right_child))) } the same topology and data
  • 30. CHAPTER 5 30 Propositional Calculus Expression  A variable is an expression.  If x and y are expressions, then ¬x, xy, xy are expressions.  Parentheses can be used to alter the normal order of evaluation (¬ >  > ).  Example: x1  (x2  ¬x3)  satisfiability problem: Is there an assignment to make an expression true?
  • 31.     X3   X1 X2 X1  X3 (x1  ¬x2)  (¬ x1  x3)  ¬x3 (t,t,t) (t,t,f) (t,f,t) (t,f,f) (f,t,t) (f,t,f) (f,f,t) (f,f,f) 2n possible combinations for n variables postorder traversal (postfix evaluation)
  • 32. left_child data value right_child typedef emun {not, and, or, true, false } logical; typedef struct node *tree_pointer; typedef struct node { tree_pointer list_child; logical data; short int value; tree_pointer right_child; } ; node structure
  • 33. for (all 2n possible combinations) { generate the next combination; replace the variables by their values; evaluate root by traversing it in postorder; if (root->value) { printf(<combination>); return; } } printf(“No satisfiable combination n”); First version of satisfiability algorithm
  • 34. void post_order_eval(tree_pointer node) { /* modified post order traversal to evaluate a propositional calculus tree */ if (node) { post_order_eval(node->left_child); post_order_eval(node->right_child); switch(node->data) { case not: node->value = !node->right_child->value; break; Post-order-eval function
  • 35. case and: node->value = node->right_child->value && node->left_child->value; break; case or: node->value = node->right_child->value | | node->left_child->value; break; case true: node->value = TRUE; break; case false: node->value = FALSE; } } }
  • 36. CHAPTER 5 36 Threaded Binary Trees  Two many null pointers in current representation of binary trees n: number of nodes number of non-null links: n-1 total links: 2n null links: 2n-(n-1)=n+1  Replace these null pointers with some useful “threads”.
  • 37. CHAPTER 5 37 Threaded Binary Trees (Continued) If ptr->left_child is null, replace it with a pointer to the node that would be visited before ptr in an inorder traversal If ptr->right_child is null, replace it with a pointer to the node that would be visited after ptr in an inorder traversal
  • 38. CHAPTER 5 38 A Threaded Binary Tree A B C G E I D H F root dangling dangling inorder traversal: H, D, I, B, E, A, F, C, G
  • 39. TRUE   FALSE Data Structures for Threaded BT typedef struct threaded_tree *threaded_pointer; typedef struct threaded_tree { short int left_thread; threaded_pointer left_child; char data; threaded_pointer right_child; short int right_thread; }; left_thread left_child data right_child right_thread FALSE: child TRUE: thread
  • 40. CHAPTER 5 40 Memory Representation of A Threaded BT f f -- f f A f f C f f B t t E t t F t G f f D t t I t t H root
  • 41. CHAPTER 5 41 Next Node in Threaded BT threaded_pointer insucc(threaded_pointer tree) { threaded_pointer temp; temp = tree->right_child; if (!tree->right_thread) while (!temp->left_thread) temp = temp->left_child; return temp; }
  • 42. CHAPTER 5 42 Inorder Traversal of Threaded BT void tinorder(threaded_pointer tree) { /* traverse the threaded binary tree inorder */ threaded_pointer temp = tree; for (;;) { temp = insucc(temp); if (temp==tree) break; printf(“%3c”, temp->data); } } O(n)
  • 43. CHAPTER 5 43 Inserting Nodes into Threaded BTs  Insert child as the right child of node parent – change parent->right_thread to FALSE – set child->left_thread and child->right_thread to TRUE – set child->left_child to point to parent – set child->right_child to parent->right_child – change parent->right_child to point to child
  • 44. CHAPTER 5 44 Examples root parent A B C D child root parent A B C D child empty Insert a node D as a right child of B. (1) (2) (3)
  • 45. *Figure 5.24: Insertion of child as a right child of parent in a threaded binary tree (p.217) nonempty (1) (3) (4) (2)
  • 46. CHAPTER 5 46 Right Insertion in Threaded BTs void insert_right(threaded_pointer parent, threaded_pointer child) { threaded_pointer temp; child->right_child = parent->right_child; child->right_thread = parent->right_thread; child->left_child = parent; case (a) child->left_thread = TRUE; parent->right_child = child; parent->right_thread = FALSE; if (!child->right_thread) { case (b) temp = insucc(child); temp->left_child = child; } } (1) (2) (3) (4)
  • 47. CHAPTER 5 47 Heap  A max tree is a tree in which the key value in each node is no smaller than the key values in its children. A max heap is a complete binary tree that is also a max tree.  A min tree is a tree in which the key value in each node is no larger than the key values in its children. A min heap is a complete binary tree that is also a min tree.  Operations on heaps – creation of an empty heap – insertion of a new element into the heap; – deletion of the largest element from the heap
  • 48. *Figure 5.25: Sample max heaps (p.219) [4] 14 12 7 8 10 6 9 6 3 5 30 25 [1] [2] [3] [5] [6] [1] [2] [3] [4] [1] [2] Property: The root of max heap (min heap) contains the largest (smallest).
  • 49. 2 7 4 8 10 6 10 20 83 50 11 21 [1] [2] [3] [5] [6] [1] [2] [3] [4] [1] [2] [4] *Figure 5.26:Sample min heaps (p.220)
  • 50. CHAPTER 5 50 ADT for Max Heap structure MaxHeap objects: a complete binary tree of n > 0 elements organized so that the value in each node is at least as large as those in its children functions: for all heap belong to MaxHeap, item belong to Element, n, max_size belong to integer MaxHeap Create(max_size)::= create an empty heap that can hold a maximum of max_size elements Boolean HeapFull(heap, n)::= if (n==max_size) return TRUE else return FALSE MaxHeap Insert(heap, item, n)::= if (!HeapFull(heap,n)) insert item into heap and return the resulting heap else return error Boolean HeapEmpty(heap, n)::= if (n>0) return FALSE else return TRUE Element Delete(heap,n)::= if (!HeapEmpty(heap,n)) return one instance of the largest element in the heap and remove it from the heap else return error
  • 51. CHAPTER 5 51 Application: priority queue  machine service – amount of time (min heap) – amount of payment (max heap)  factory – time tag
  • 52. CHAPTER 5 52 Data Structures  unordered linked list  unordered array  sorted linked list  sorted array  heap
  • 53. Representation Insertion Deletion Unordered array (1) (n) Unordered linked list (1) (n) Sorted array O(n) (1) Sorted linked list O(n) (1) Max heap O(log2n) O(log2n) *Figure 5.27: Priority queue representations (p.221)
  • 54. CHAPTER 5 54 Example of Insertion to Max Heap 20 15 2 14 10 initial location of new node 21 15 20 14 10 2 insert 21 into heap 20 15 5 14 10 2 insert 5 into heap
  • 55. CHAPTER 5 55 Insertion into a Max Heap void insert_max_heap(element item, int *n) { int i; if (HEAP_FULL(*n)) { fprintf(stderr, “the heap is full.n”); exit(1); } i = ++(*n); while ((i!=1)&&(item.key>heap[i/2].key)) { heap[i] = heap[i/2]; i /= 2; } heap[i]= item; } 2k -1=n ==> k=log2(n+1) O(log2n)
  • 56. CHAPTER 5 56 Example of Deletion from Max Heap 20 remove 15 2 14 10 10 15 2 14 15 14 2 10
  • 57. CHAPTER 5 57 Deletion from a Max Heap element delete_max_heap(int *n) { int parent, child; element item, temp; if (HEAP_EMPTY(*n)) { fprintf(stderr, “The heap is emptyn”); exit(1); } /* save value of the element with the highest key */ item = heap[1]; /* use last element in heap to adjust heap temp = heap[(*n)--]; parent = 1; child = 2;
  • 58. CHAPTER 5 58 while (child <= *n) { /* find the larger child of the current parent */ if ((child < *n)&& (heap[child].key<heap[child+1].key)) child++; if (temp.key >= heap[child].key) break; /* move to the next lower level */ heap[parent] = heap[child]; child *= 2; } heap[parent] = temp; return item; }
  • 59. CHAPTER 5 59 Binary Search Tree  Heap – a min (max) element is deleted. O(log2n) – deletion of an arbitrary element O(n) – search for an arbitrary element O(n)  Binary search tree – Every element has a unique key. – The keys in a nonempty left subtree (right subtree) are smaller (larger) than the key in the root of subtree. – The left and right subtrees are also binary search trees.
  • 60. CHAPTER 5 60 Examples of Binary Search Trees 20 12 25 10 15 30 5 40 2 60 70 65 80 22
  • 61. CHAPTER 5 61 Searching a Binary Search Tree tree_pointer search(tree_pointer root, int key) { /* return a pointer to the node that contains key. If there is no such node, return NULL */ if (!root) return NULL; if (key == root->data) return root; if (key < root->data) return search(root->left_child, key); return search(root->right_child,key); }
  • 62. CHAPTER 5 62 Another Searching Algorithm tree_pointer search2(tree_pointer tree, int key) { while (tree) { if (key == tree->data) return tree; if (key < tree->data) tree = tree->left_child; else tree = tree->right_child; } return NULL; } O(h)
  • 63. CHAPTER 5 63 Insert Node in Binary Search Tree 30 5 40 2 30 5 40 2 35 80 30 5 40 2 80 Insert 80 Insert 35
  • 64. CHAPTER 5 64 Insertion into A Binary Search Tree void insert_node(tree_pointer *node, int num) {tree_pointer ptr, temp = modified_search(*node, num); if (temp || !(*node)) { ptr = (tree_pointer) malloc(sizeof(node)); if (IS_FULL(ptr)) { fprintf(stderr, “The memory is fulln”); exit(1); } ptr->data = num; ptr->left_child = ptr->right_child = NULL; if (*node) if (num<temp->data) temp->left_child=ptr; else temp->right_child = ptr; else *node = ptr; } }
  • 65. CHAPTER 5 65 Deletion for A Binary Search Tree leaf node 30 5 2 80 2 T1 T2 1 X T2 1 T1
  • 66. CHAPTER 5 66 Deletion for A Binary Search Tree 40 20 60 10 30 50 70 45 55 52 40 20 55 10 30 50 70 45 52 Before deleting 60 After deleting 60 non-leaf node
  • 67. CHAPTER 5 67 1 2 T1 T2 T3 1 2‘ T1 T2’ T3
  • 68. CHAPTER 5 68 Selection Trees (1) winner tree (2) loser tree
  • 69. CHAPTER 5 69 winner tree 6 6 8 9 6 8 17 8 9 90 17 20 6 10 9 15 16 20 38 20 30 15 25 15 50 11 16 100 110 18 20 run 1 run 2 run 3 run 4 run 5 run 6 run 7 run 8 ordered sequence sequential allocation scheme (complete binary tree) Each node represents the smaller of its two children. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  • 70. *Figure 5.35: Selection tree of Figure 5.34 after one record has been output and the tree restructured(nodes that were changed are ticked) 15 16 20 30 15 50 25 25 20 38 11 16 100 110 18 20 10 8 9 9 20 10 15 11 8 12 9 13 90 14 17 15 9 4 15 5  8 6 17 7 9 2  8 3 8 1 
  • 71. CHAPTER 5 71 Analysis  K: # of runs  n: # of records  setup time: O(K) (K-1)  restructure time: O(log2K) log2(K+1)  merge time: O(nlog2K)  slight modification: tree of loser – consider the parent node only (vs. sibling nodes)
  • 72. 10 8 9 9 20 10 6 11 8 12 9 13 90 14 17 15 10 4 20 5 9 6 90 7 9 2 17 3 8 1 6 Run 1 2 3 4 5 6 7 8 overall winner *Figure 5.36: Tree of losers corresponding to Figure 5.34 (p.235) 15 15 9 8 15 15 9
  • 73. CHAPTER 5 73 Forest  A forest is a set of n >= 0 disjoint trees A E G B C D F H I G H I A B C D F E Forest
  • 74. CHAPTER 5 74 Transform a forest into a binary tree  T1, T2, …, Tn: a forest of trees B(T1, T2, …, Tn): a binary tree corresponding to this forest  algorithm (1) empty, if n = 0 (2) has root equal to root(T1) has left subtree equal to B(T11,T12,…,T1m) has right subtree equal to B(T2,T3,…,Tn)
  • 75. CHAPTER 5 75 Forest Traversals  Preorder – If F is empty, then return – Visit the root of the first tree of F – Taverse the subtrees of the first tree in tree preorder – Traverse the remaining trees of F in preorder  Inorder – If F is empty, then return – Traverse the subtrees of the first tree in tree inorder – Visit the root of the first tree – Traverse the remaining trees of F is indorer
  • 76. CHAPTER 5 76 D H A B F G C E I J inorder: EFBGCHIJDA preorder: ABEFCGDHIJ A B C D E F G H I J B E F C G D H I J preorde r
  • 77. CHAPTER 5 77 Set Representation  S1={0, 6, 7, 8}, S2={1, 4, 9}, S3={2, 3, 5}  Two operations considered here – Disjoint set union S1  S2={0,6,7,8,1,4,9} – Find(i): Find the set containing the element i. 3  S3, 8  S1 0 6 7 8 1 4 9 2 3 5 Si  Sj = 
  • 78. CHAPTER 5 78 Disjoint Set Union 1 4 9 0 6 7 8 1 4 9 0 6 7 8 Possible representation for S1 union S2 Make one of trees a subtree of the other
  • 79. 0 6 7 8 4 1 9 2 3 5 set name pointer S1 S2 S3 *Figure 5.41:Data Representation of S1S2and S3 (p.240)
  • 80. CHAPTER 5 80 Array Representation for Set int find1(int i) { for (; parent[i]>=0; i=parent[i]) return i; } void union1(int i, int j) { parent[i]= j; } i [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] parent -1 4 -1 2 -1 2 0 0 0 4
  • 81. n-1 n-2 0    *Figure 5.43:Degenerate tree (p.242) union operation O(n) n-1 find operation O(n2 ) i i n   2 union(0,1), find(0) union(1,2), find(0) . . . union(n-2,n-1),find(0) degenerate tree
  • 82. *Figure 5.44:Trees obtained using the weighting rule(p.243) weighting rule for union(i,j): if # of nodes in i < # in j then j the parent of i
  • 83. CHAPTER 5 83 Modified Union Operation void union2(int i, int j) { int temp = parent[i]+parent[j]; if (parent[i]>parent[j]) { parent[i]=j; parent[j]=temp; } else { parent[j]=i; parent[i]=temp; } } If the number of nodes in tree i is less than the number in tree j, then make j the parent of i; otherwise make i the parent of j. Keep a count in the root of tree i has fewer nodes. j has fewer nodes
  • 84. Figure 5.45:Trees achieving worst case bound (p.245)  log28+1
  • 85. CHAPTER 5 85 Modified Find(i) Operation int find2(int i) { int root, trail, lead; for (root=i; parent[root]>=0; root=parent[root]); for (trail=i; trail!=root; trail=lead) { lead = parent[trail]; parent[trail]= root; } return root: } If j is a node on the path from i to its root then make j a child of the root
  • 86. CHAPTER 5 86 0 1 2 4 3 5 6 7 0 1 2 4 3 5 6 7 find(7) find(7) find(7) find(7) find(7) find(7) find(7) find(7) go up 3 1 1 1 1 1 1 1 reset 2 12 moves (vs. 24 moves)
  • 87. CHAPTER 5 87 Applications  Find equivalence class i  j  Find Si and Sj such that i  Si and j  Sj (two finds) – Si = Sj do nothing – Si  Sj union(Si , Sj)  example 0  4, 3  1, 6  10, 8  9, 7  4, 6  8, 3  5, 2  11, 11  0 {0, 2, 4, 7, 11}, {1, 3, 5}, {6, 8, 9, 10}
  • 88. CHAPTER 5 88 preorder: A B C D E F G H I inorder: B C A E D G H F I A B, C D, E, F, G, H, I A D, E, F, G, H, I B C A B C D E F G I H
  • 89. CHAPTER 6 89 CHAPTER 6 GRAPHS All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals of Data Structures in C”, Computer Science Press, 1992.
  • 90. CHAPTER 6 90 Definition  A graph G consists of two sets – a finite, nonempty set of vertices V(G) – a finite, possible empty set of edges E(G) – G(V,E) represents a graph  An undirected graph is one in which the pair of vertices in a edge is unordered, (v0, v1) = (v1,v0)  A directed graph is one in which each edge is a directed pair of vertices, <v0, v1> != <v1,v0> tail head
  • 91. CHAPTER 6 91 Examples for Graph 0 1 2 3 0 1 2 0 1 2 3 4 5 6 G1 G2 G3 V(G1)={0,1,2,3} E(G1)={(0,1),(0,2),(0,3),(1,2),(1,3),(2,3)} V(G2)={0,1,2,3,4,5,6} E(G2)={(0,1),(0,2),(1,3),(1,4),(2,5),(2,6)} V(G3)={0,1,2} E(G3)={<0,1>,<1,0>,<1,2>} complete undirected graph: n(n-1)/2 edges complete directed graph: n(n-1) edges complete graph incomplete graph
  • 92. CHAPTER 6 92 Complete Graph  A complete graph is a graph that has the maximum number of edges – for undirected graph with n vertices, the maximum number of edges is n(n-1)/2 – for directed graph with n vertices, the maximum number of edges is n(n-1) – example: G1 is a complete graph
  • 93. CHAPTER 6 93 Adjacent and Incident  If (v0, v1) is an edge in an undirected graph, – v0 and v1 are adjacent – The edge (v0, v1) is incident on vertices v0 and v1  If <v0, v1> is an edge in a directed graph – v0 is adjacent to v1, and v1 is adjacent from v0 – The edge <v0, v1> is incident on v0 and v1
  • 94. CHAPTER 6 94 0 2 1 (a) 2 1 0 3 (b) *Figure 6.3:Example of a graph with feedback loops and a multigraph (p.260) self edge multigraph: multiple occurrences of the same edge Figure 6.3
  • 95. CHAPTER 6 95  A subgraph of G is a graph G’ such that V(G’) is a subset of V(G) and E(G’) is a subset of E(G)  A path from vertex vp to vertex vq in a graph G, is a sequence of vertices, vp, vi1, vi2, ..., vin, vq, such that (vp, vi1), (vi1, vi2), ..., (vin, vq) are edges in an undirected graph  The length of a path is the number of edges on it Subgraph and Path
  • 96. CHAPTER 6 96 0 0 1 2 3 1 2 0 1 2 3 (i) (ii) (iii) (iv) (a) Some of the subgraph of G1 0 0 1 0 1 2 0 1 2 (i) (ii) (iii) (iv) (b) Some of the subgraph of G3 分開 單一 0 1 2 3 G1 0 1 2 G3 Figure 6.4: subgraphs of G1 and G3 (p.261)
  • 97. CHAPTER 6 97  A simple path is a path in which all vertices, except possibly the first and the last, are distinct  A cycle is a simple path in which the first and the last vertices are the same  In an undirected graph G, two vertices, v0 and v1, are connected if there is a path in G from v0 to v1  An undirected graph is connected if, for every pair of distinct vertices vi, vj, there is a path from vi to vj Simple Path and Style
  • 98. CHAPTER 6 98 0 1 2 3 0 1 2 3 4 5 6 G1 G2 connected tree (acyclic graph)
  • 99. CHAPTER 6 99  A connected component of an undirected graph is a maximal connected subgraph.  A tree is a graph that is connected and acyclic.  A directed graph is strongly connected if there is a directed path from vi to vj and also from vj to vi.  A strongly connected component is a maximal subgraph that is strongly connected. Connected Component
  • 100. CHAPTER 6 100 *Figure 6.5: A graph with two connected components (p.262) 1 0 2 3 4 5 6 7 H1 H2 G4 (not connected) connected component (maximal connected subgraph)
  • 101. CHAPTER 6 101 *Figure 6.6: Strongly connected components of G3 (p.262) 0 1 2 0 1 2 G3 not strongly connected strongly connected component (maximal strongly connected subgraph)
  • 102. CHAPTER 6 102 Degree  The degree of a vertex is the number of edges incident to that vertex  For directed graph, – the in-degree of a vertex v is the number of edges that have v as the head – the out-degree of a vertex v is the number of edges that have v as the tail – if di is the degree of a vertex i in a graph G with n vertices and e edges, the number of edges is e di n    ( ) / 0 1 2
  • 103. CHAPTER 6 103 undirected graph degree 0 1 2 3 4 5 6 G1 G2 3 2 3 3 1 1 1 1 directed graph in-degree out-degree 0 1 2 G3 in:1, out: 1 in: 1, out: 2 in: 1, out: 0 0 1 2 3 3 3 3
  • 104. CHAPTER 6 104 ADT for Graph structure Graph is objects: a nonempty set of vertices and a set of undirected edges, where each edge is a pair of vertices functions: for all graph  Graph, v, v1 and v2  Vertices Graph Create()::=return an empty graph Graph InsertVertex(graph, v)::= return a graph with v inserted. v has no incident edge. Graph InsertEdge(graph, v1,v2)::= return a graph with new edge between v1 and v2 Graph DeleteVertex(graph, v)::= return a graph in which v and all edges incident to it are removed Graph DeleteEdge(graph, v1, v2)::=return a graph in which the edge (v1, v2) is removed Boolean IsEmpty(graph)::= if (graph==empty graph) return TRUE else return FALSE List Adjacent(graph,v)::= return a list of all vertices that are adjacent to v
  • 105. CHAPTER 6 105 Graph Representations  Adjacency Matrix  Adjacency Lists  Adjacency Multilists
  • 106. CHAPTER 6 106 Adjacency Matrix  Let G=(V,E) be a graph with n vertices.  The adjacency matrix of G is a two-dimensional n by n array, say adj_mat  If the edge (vi, vj) is in E(G), adj_mat[i][j]=1  If there is no such edge in E(G), adj_mat[i][j]=0  The adjacency matrix for an undirected graph is symmetric; the adjacency matrix for a digraph need not be symmetric
  • 107. CHAPTER 6 107 Examples for Adjacency Matrix 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0             0 1 0 1 0 0 0 1 0           0 1 1 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0                           G1 G2 G4 0 1 2 3 0 1 2 1 0 2 3 4 5 6 7 symmetric undirected: n2 /2 directed: n2
  • 108. CHAPTER 6 108 Merits of Adjacency Matrix  From the adjacency matrix, to determine the connection of vertices is easy  The degree of a vertex is  For a digraph, the row sum is the out_degree, while the column sum is the in_degree adj mat i j j n _ [ ][ ]    0 1 ind vi A j i j n ( ) [ , ]     0 1 outd vi A i j j n ( ) [ , ]     0 1
  • 109. CHAPTER 6 109 Data Structures for Adjacency Lists #define MAX_VERTICES 50 typedef struct node *node_pointer; typedef struct node { int vertex; struct node *link; }; node_pointer graph[MAX_VERTICES]; int n=0; /* vertices currently in use * Each row in adjacency matrix is represented as an adjacency list.
  • 110. CHAPTER 6 110 0 1 2 3 0 1 2 0 1 2 3 4 5 6 7 1 2 3 0 2 3 0 1 3 0 1 2 G1 1 0 2 G3 1 2 0 3 0 3 1 2 5 4 6 5 7 6 G4 0 1 2 3 0 1 2 1 0 2 3 4 5 6 7 An undirected graph with n vertices and e edges ==> n head nodes and 2e list nodes
  • 111. CHAPTER 6 111 Interesting Operations degree of a vertex in an undirected graph –# of nodes in adjacency list # of edges in a graph –determined in O(n+e) out-degree of a vertex in a directed graph –# of nodes in its adjacency list in-degree of a vertex in a directed graph –traverse the whole data structure
  • 112. CHAPTER 6 112 [0] 9 [8] 23 [16] 2 [1] 11 [9] 1 [17] 5 [2] 13 [10] 2 [18] 4 [3] 15 [11] 0 [19] 6 [4] 17 [12] 3 [20] 5 [5] 18 [13] 0 [21] 7 [6] 20 [14] 3 [22] 6 [7] 22 [15] 1 1 0 2 3 4 5 6 7 0 1 2 3 4 5 6 7 node[0] … node[n-1]: starting point for vertices node[n]: n+2e+1 node[n+1] … node[n+2e]: head node of edge Compact Representation
  • 113. CHAPTER 6 113    0 1 2 1 NULL 0 NULL 1 NULL 0 1 2 Determine in-degree of a vertex in a fast way. Figure 6.10: Inverse adjacency list for G3
  • 114. CHAPTER 6 114 tail head column link for head row link for tail Figure 6.11: Alternate node structure for adjacency lists (p.267)
  • 115. CHAPTER 6 115 0 1 2 2 NULL 1 0 1 0NULL 0 1 NULL NULL 1 2 NULL NULL 0 1 2 0 1 0 1 0 0 0 1 0           Figure 6.12: Orthogonal representation for graph G3(p.268)
  • 116. CHAPTER 6 116  3  2 NULL 1  0  2  3 NULL 0  1  3  1 NULL 0  2  2  0 NULL 1  3 headnodes vertax link Order is of no significance. 0 1 2 3 Figure 6.13:Alternate order adjacency list for G1 (p.268)
  • 117. CHAPTER 6 117 Adjacency Multilists marked vertex1 vertex2 path1 path2 An edge in an undirected graph is represented by two nodes in adjacency list representation. Adjacency Multilists –lists in which nodes may be shared among several lists. (an edge is shared by two different paths)
  • 118. CHAPTER 6 118 0 1 N2 N4 0 2 N3 N4 0 3 N5 1 2 N5 N6 1 3 N6 2 3 N1 N2 N3 N4 N5 N6 0 1 2 3 edge (0,1) edge (0,2) edge (0,3) edge (1,2) edge (1,3) edge (2,3) (1,0) (2,0) (3,0) (2,1) (3,1) (3,2) 0 1 2 3 six edges Lists: vertex 0: M1->M2->M3, vertex 1: M1->M4->M5 vertex 2: M2->M4->M6, vertex 3: M3->M5->M6 Example for Adjacency Multlists
  • 119. CHAPTER 6 119 typedef struct edge *edge_pointer; typedef struct edge { short int marked; int vertex1, vertex2; edge_pointer path1, path2; }; edge_pointer graph[MAX_VERTICES]; marked vertex1 vertex2 path1 path2 Adjacency Multilists
  • 120. CHAPTER 6 120 Some Graph Operations  Traversal Given G=(V,E) and vertex v, find all wV, such that w connects v. – Depth First Search (DFS) preorder tree traversal – Breadth First Search (BFS) level order tree traversal  Connected Components  Spanning Trees
  • 121. CHAPTER 6 121 *Figure 6.19:Graph G and its adjacency lists (p.274) depth first search: v0, v1, v3, v7, v4, v5, v2, v6 breadth first search: v0, v1, v2, v3, v4, v5, v6, v7
  • 122. CHAPTER 6 122 Depth First Search void dfs(int v) { node_pointer w; visited[v]= TRUE; printf(“%5d”, v); for (w=graph[v]; w; w=w->link) if (!visited[w->vertex]) dfs(w->vertex); } #define FALSE 0 #define TRUE 1 short int visited[MAX_VERTICES]; Data structure adjacency list: O(e) adjacency matrix: O(n2 )
  • 123. CHAPTER 6 123 Breadth First Search typedef struct queue *queue_pointer; typedef struct queue { int vertex; queue_pointer link; }; void addq(queue_pointer *, queue_pointer *, int); int deleteq(queue_pointer *);
  • 124. CHAPTER 6 124 Breadth First Search (Continued) void bfs(int v) { node_pointer w; queue_pointer front, rear; front = rear = NULL; printf(“%5d”, v); visited[v] = TRUE; addq(&front, &rear, v); adjacency list: O(e) adjacency matrix: O(n2 )
  • 125. CHAPTER 6 125 while (front) { v= deleteq(&front); for (w=graph[v]; w; w=w->link) if (!visited[w->vertex]) { printf(“%5d”, w->vertex); addq(&front, &rear, w->vertex); visited[w->vertex] = TRUE; } } }
  • 126. CHAPTER 6 126 Connected Components void connected(void) { for (i=0; i<n; i++) { if (!visited[i]) { dfs(i); printf(“n”); } } } adjacency list: O(n+e) adjacency matrix: O(n2 )
  • 127. CHAPTER 6 127 Spanning Trees  When graph G is connected, a depth first or breadth first search starting at any vertex will visit all vertices in G  A spanning tree is any tree that consists solely of edges in G and that includes all the vertices  E(G): T (tree edges) + N (nontree edges) where T: set of edges used during search N: set of remaining edges
  • 128. CHAPTER 6 128 Examples of Spanning Tree 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 G1 Possible spanning trees
  • 129. CHAPTER 6 129 Spanning Trees  Either dfs or bfs can be used to create a spanning tree – When dfs is used, the resulting spanning tree is known as a depth first spanning tree – When bfs is used, the resulting spanning tree is known as a breadth first spanning tree  While adding a nontree edge into any spanning tree, this will create a cycle
  • 130. CHAPTER 6 130 DFS VS BFS Spanning Tree 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 DFS Spanning BFS Spanning 0 1 2 3 4 5 6 7 nontree edge cycle
  • 131. CHAPTER 6 131 A spanning tree is a minimal subgraph, G’, of G such that V(G’)=V(G) and G’ is connected. Any connected graph with n vertices must have at least n-1 edges. A biconnected graph is a connected graph that has no articulation points. 0 1 2 3 4 5 6 7 biconnected graph
  • 132. CHAPTER 6 132 1 3 5 6 0 8 9 7 2 4 connected graph 1 3 5 6 0 8 9 7 2 4 1 3 5 6 0 8 9 7 2 4 two connected components one connected graph
  • 133. CHAPTER 6 133 biconnected component: a maximal connected subgraph H (no subgraph that is both biconnected and properly contains H) 1 3 5 6 0 8 9 7 2 4 1 0 1 3 2 4 3 5 8 7 9 7 5 6 7 biconnected components
  • 134. CHAPTER 6 134 Find biconnected component of a connected undirected graph by depth first spanning tree 8 9 1 4 0 3 0 5 3 5 4 6 1 6 9 8 9 8 7 7 3 4 5 7 6 9 8 2 0 1 0 6 7 1 5 2 4 3 (a) depth first spanning tree (b) 2 2 dfn depth first number nontree edge (back edge) nontree edge (back edge) Why is cross edge impossible? If u is an ancestor of v then dfn(u) < dfn(v).
  • 135. CHAPTER 6 135 *Figure 6.24: dfn and low values for dfs spanning tree with root =3(p.281) Vertax 0 1 2 3 4 5 6 7 8 9 dfn 4 3 2 0 1 5 6 7 9 8 low 4 0 0 0 0 5 5 5 9 8
  • 136. CHAPTER 6 136 8 9 3 4 5 7 6 9 8 2 0 1 0 6 7 1 5 2 4 3 low(u)=min{dfn(u), min{low(w)|w is a child of u}, min{dfn(w)|(u,w) is a back edge} u: articulation point low(child)  dfn(u) *The root of a depth first spanning tree is an articulation point iff it has at least two children. *Any other vertex u is an articulation point iff it has at least one child w such that we cannot reach an ancestor of u using a path that consists of (1) only w (2) descendants of w (3) single back edge.
  • 137. CHAPTER 6 137 8 9 3 4 5 7 6 9 8 2 0 1 6 7 1 5 2 4 3 vertex dfn low child low_child low:dfn 0 4 4 (4,n,n) null null null:4 1 3 0 (3,4,0) 0 4 4 3  2 2 0 (2,0,n) 1 0 0 < 2 3 0 0 (0,0,n) 4,5 0,5 0,5 0  4 1 0 (1,0,n) 2 0 0 < 1 5 5 5 (5,5,n) 6 5 5 5  6 6 5 (6,5,n) 7 5 5 < 6 7 7 5 (7,8,5) 8,9 9,8 9,8 7  8 9 9 (9,n,n) null null null, 9 9 8 8 (8,n,n) null null null, 8
  • 138. CHAPTER 6 138 *Program 6.5: Initializaiton of dfn and low (p.282) void init(void) { int i; for (i = 0; i < n; i++) { visited[i] = FALSE; dfn[i] = low[i] = -1; } num = 0; }
  • 139. CHAPTER 6 139 *Program 6.4: Determining dfn and low (p.282) Initial call: dfn(x,-1) low[u]=min{dfn(u), …} low[u]=min{…, min{low(w)|w is a child of u}, …} low[u]=min{…,…,min{dfn(w)|(u,w) is a back edge} dfn[w]0 非第一次,表示藉 back edge v u w v u X O void dfnlow(int u, int v) { /* compute dfn and low while performing a dfs search beginning at vertex u, v is the parent of u (if any) */ node_pointer ptr; int w; dfn[u] = low[u] = num++; for (ptr = graph[u]; ptr; ptr = ptr ->link) { w = ptr ->vertex; if (dfn[w] < 0) { /*w is an unvisited vertex */ dfnlow(w, u); low[u] = MIN2(low[u], low[w]); } else if (w != v) low[u] =MIN2(low[u], dfn[w] ); } }
  • 140. CHAPTER 6 140 *Program 6.6: Biconnected components of a graph (p.283) low[u]=min{dfn(u), …} (1) dfn[w]=-1 第一次 (2) dfn[w]!=-1 非第一次,藉 back edge void bicon(int u, int v) { /* compute dfn and low, and output the edges of G by their biconnected components , v is the parent ( if any) of the u (if any) in the resulting spanning tree. It is assumed that all entries of dfn[ ] have been initialized to -1, num has been initialized to 0, and the stack has been set to empty */ node_pointer ptr; int w, x, y; dfn[u] = low[u] = num ++; for (ptr = graph[u]; ptr; ptr = ptr->link) { w = ptr ->vertex; if ( v != w && dfn[w] < dfn[u] ) add(&top, u, w); /* add edge to stack */
  • 141. CHAPTER 6 141 if(dfn[w] < 0) {/* w has not been visited */ bicon(w, u); low[u] = MIN2(low[u], low[w]); if (low[w] >= dfn[u] ){ articulation point printf(“New biconnected component: “); do { /* delete edge from stack */ delete(&top, &x, &y); printf(“ <%d, %d>” , x, y); } while (!(( x = = u) && (y = = w))); printf(“n”); } } else if (w != v) low[u] = MIN2(low[u], dfn[w]); } } low[u]=min{…, …, min{dfn(w)|(u,w) is a back edge}} low[u]=min{…, min{low(w)|w is a child of u}, …
  • 142. CHAPTER 6 142 Minimum Cost Spanning Tree  The cost of a spanning tree of a weighted undirected graph is the sum of the costs of the edges in the spanning tree  A minimum cost spanning tree is a spanning tree of least cost  Three different algorithms can be used – Kruskal – Prim – Sollin Select n-1 edges from a weighted graph of n vertices with minimum cost.
  • 143. CHAPTER 6 143 Greedy Strategy  An optimal solution is constructed in stages  At each stage, the best decision is made at this time  Since this decision cannot be changed later, we make sure that the decision will result in a feasible solution  Typically, the selection of an item at each stage is based on a least cost or a highest profit criterion
  • 144. CHAPTER 6 144 Kruskal’s Idea  Build a minimum cost spanning tree T by adding edges to T one at a time  Select the edges for inclusion in T in nondecreasing order of the cost  An edge is added to T if it does not form a cycle  Since G is connected and has n > 0 vertices, exactly n-1 edges will be selected
  • 145. CHAPTER 6 145 Examples for Kruskal’s Algorithm 0 1 2 3 4 5 6 0 1 2 3 4 5 6 28 16 12 18 24 22 25 10 14 0 1 2 3 4 5 6 10 0 5 2 3 1 6 1 2 3 6 3 4 4 6 4 5 10 12 14 16 18 22 24 25 28 6/9
  • 146. CHAPTER 6 146 0 1 2 3 4 5 6 10 12 0 1 2 3 4 5 6 10 12 14 0 1 2 3 4 5 6 10 12 14 16 0 5 2 3 1 6 1 2 3 6 3 4 4 6 4 5 0 1 10 12 14 16 18 22 24 25 28 + 3 6 cycle
  • 147. CHAPTER 6 147 0 5 2 3 1 6 1 2 3 6 3 4 4 6 4 5 0 1 10 12 14 16 18 22 24 25 28 0 1 2 3 4 5 6 10 12 14 16 22 0 1 2 3 4 5 6 10 12 14 16 22 25 4 6 cycle + cost = 10 +25+22+12+16+14
  • 148. CHAPTER 6 148 Kruskal’s Algorithm T= {}; while (T contains less than n-1 edges && E is not empty) { choose a least cost edge (v,w) from E; delete (v,w) from E; if ((v,w) does not create a cycle in T) add (v,w) to T else discard (v,w); } if (T contains fewer than n-1 edges) printf(“No spanning treen”); 目標:取出 n-1 條 edges min heap construction time O(e) choose and delete O(log e) find find & union O(log e) {0,5}, {1,2,3,6}, {4} + edge(3,6) X + edge(3,4) --> {0,5},{1,2,3,4,6} O(e log e)
  • 149. CHAPTER 6 149 Prim’s Algorithm T={}; TV={0}; while (T contains fewer than n-1 edges) { let (u,v) be a least cost edge such that and if (there is no such edge ) break; add v to TV; add (u,v) to T; } if (T contains fewer than n-1 edges) printf(“No spanning treen”); u TV  v TV  (tree all the time vs. forest)
  • 150. CHAPTER 6 150 Examples for Prim’s Algorithm 0 1 2 3 4 5 6 0 1 2 3 4 5 6 10 0 1 2 3 4 5 6 10 10 25 25 22 0 1 2 3 4 5 6 28 16 12 18 24 22 25 10 14
  • 151. CHAPTER 6 151 0 1 2 3 4 5 6 10 25 22 12 0 1 2 3 4 5 6 10 25 22 12 16 0 1 2 3 4 5 6 10 25 22 12 16 14 0 1 2 3 4 5 6 28 16 12 18 24 22 25 10 14
  • 152. CHAPTER 6 152 Sollin’s Algorithm 0 1 2 3 4 5 6 10 0 22 12 16 14 0 1 2 3 4 5 6 10 22 12 14 0 1 2 3 4 5 6 0 1 2 3 4 5 6 28 16 12 18 24 22 25 10 14 vertex edge 0 0 -- 10 --> 5, 0 -- 28 --> 1 1 1 -- 14 --> 6, 1-- 16 --> 2, 1 -- 28 --> 0 2 2 -- 12 --> 3, 2 -- 16 --> 1 3 3 -- 12 --> 2, 3 -- 18 --> 6, 3 -- 22 --> 4 4 4 -- 22 --> 3, 4 -- 24 --> 6, 5 -- 25 --> 5 5 5 -- 10 --> 0, 5 -- 25 --> 4 6 6 -- 14 --> 1, 6 -- 18 --> 3, 6 -- 24 --> 4 {0,5} 5 4 0 1 25 28 {1,6} 1 2 16 28 1 6 3 6 4 18 24
  • 153. CHAPTER 6 153 *Figure 6.29: Graph and shortest paths from v0 (p.293) V0 V4 V1 V5 V3 V2 50 10 20 10 15 20 35 30 15 3 45 (a) path length 1) v0 v2 10 2) v0 v2 v3 25 3) v0 v2 v3 v1 45 4) v0 v4 45 (b) Single Source All Destinations Determine the shortest paths from v0 to all the remaining vertices.
  • 154. CHAPTER 6 154 Example for the Shortest Path 0 1 2 3 4 5 6 7 San Francisco Denver Chicago Boston New York Miami New Orleans Los Angeles 300 1000 800 1200 1500 1400 1000 900 1700 1000 250 0 1 2 3 4 5 6 7 0 0 1 300 0 2 1000 800 0 3 1200 0 4 1500 0 250 5 1000 0 900 1400 6 0 1000 7 1700 0 Cost adjacency matrix
  • 155. CHAPTER 6 155 4 3 5 1500 250 4 3 5 1500 250 1000 選 5 4 到 3 由 1500 改成 1250 4 5 250 6 900 4 到 6 由改成 1250 4 5 250 7 1400 4 到 7 由改成 1650 4 5 250 6 900 7 1400 3 1000 選 6 4 5 250 6 900 7 1400 1000 4-5-6-7 比 4-5-7 長 (a) (b) (c) (d) (e) (f)
  • 156. CHAPTER 6 156 4 5 250 6 900 7 1400 3 1000 選 3 4 5 250 6 900 7 1400 3 1000 2 1200 4 到 2 由改成 2450 4 5 250 6 900 7 1400 3 1000 2 1200 選 7 4 5 250 7 1400 0 4 到 0 由改成 3350 (g) (h) (i) (j)
  • 157. CHAPTER 6 157 Example for the Shortest Path (Continued) Iteration S Vertex Selected LA [0] SF [1] DEN [2] CHI [3] BO [4] NY [5] MIA [6] NO Initial -- ---- + + + 1500 0 250 + + 1 {4} 5 + + + 1250 0 250 1150 1650 2 {4,5} 6 + + + 1250 0 250 1150 1650 3 {4,5,6} 3 + + 2450 1250 0 250 1150 1650 4 {4,5,6,3} 7 3350 + 2450 1250 0 250 1150 1650 5 {4,5,6,3,7} 2 3350 3250 2450 1250 0 250 1150 1650 6 {4,5,6,3,7,2} 1 3350 3250 2450 1250 0 250 1150 1650 7 {4,5,6,3,7,2,1} (a) (b) (c) (d) (e) (f) (g) (h) (i) (j)
  • 158. CHAPTER 6 158 Data Structure for SSAD #define MAX_VERTICES 6 int cost[][MAX_VERTICES]= {{ 0, 50, 10, 1000, 45, 1000}, {1000, 0, 15, 1000, 10, 1000}, { 20, 1000, 0, 15, 1000, 1000}, {1000, 20, 1000, 0, 35, 1000}, {1000, 1000, 30, 1000, 0, 1000}, {1000, 1000, 1000, 3, 1000, 0}}; int distance[MAX_VERTICES]; short int found{MAX_VERTICES]; int n = MAX_VERTICES; adjacency matrix
  • 159. CHAPTER 6 159 Single Source All Destinations void shortestpath(int v, int cost[] [MAX_ERXTICES], int distance[], int n, short int found[]) { int i, u, w; for (i=0; i<n; i++) { found[i] = FALSE; distance[i] = cost[v][i]; } found[v] = TRUE; distance[v] = 0; O(n)
  • 160. CHAPTER 6 160 for (i=0; i<n-2; i++) {determine n-1 paths from v u = choose(distance, n, found); found[u] = TRUE; for (w=0; w<n; w++) if (!found[w]) if (distance[u]+cost[u][w]<distance[w]) distance[w] = distance[u]+cost[u][w]; } } O(n2 ) 與 u 相連的端點 w
  • 161. CHAPTER 6 161 All Pairs Shortest Paths Find the shortest paths between all pairs of vertices. Solution 1 –Apply shortest path n times with each vertex as source. O(n3 ) Solution 2 –Represent the graph G by its cost adjacency matrix with cost[i][j] –If the edge <i,j> is not in G, the cost[i][j] is set to some sufficiently large number –A[i][j] is the cost of the shortest path form i to j, using only those intermediate vertices with an index <= k
  • 162. CHAPTER 6 162 All Pairs Shortest Paths (Continued)  The cost of the shortest path from i to j is A [i][j], as no vertex in G has an index greater than n-1  A [i][j]=cost[i][j]  Calculate the A, A, A, ..., A from A iteratively  A [i][j]=min{A [i][j], A [i][k]+A [k][j]}, k>=0 n-1 -1 0 1 2 n-1 -1 k k-1 k-1 k-1
  • 163. CHAPTER 6 163 Graph with negative cycle 0 1 2 -2 1 1 (a) Directed graph (b) A-1               0 1 0 2 1 0 The length of the shortest path from vertex 0 to vertex 2 is -. 0, 1, 0, 1,0, 1, …, 0, 1, 2
  • 164. CHAPTER 6 164 Algorithm for All Pairs Shortest Paths void allcosts(int cost[][MAX_VERTICES], int distance[][MAX_VERTICES], int n) { int i, j, k; for (i=0; i<n; i++) for (j=0; j<n; j++) distance[i][j] = cost[i][j]; for (k=0; k<n; k++) for (i=0; i<n; i++) for (j=0; j<n; j++) if (distance[i][k]+distance[k][j] < distance[i][j]) distance[i][j]= distance[i][k]+distance[k][j]; }
  • 165. CHAPTER 6 165 * Figure 6.33: Directed graph and its cost matrix (p.299) V0 V2 V1 6 4 3 11 2 (a)Digraph G (b)Cost adjacency matrix for G 0 1 2 0 0 4 11 1 6 0 2 2 3  0
  • 166. CHAPTER 6 166 0 1 2 0 0 4 11 1 6 0 2 2 3  0 A-1 0 1 2 0 0 4 11 1 6 0 2 2 3 7 0 A0 0 1 2 0 0 4 6 1 6 0 2 2 3 7 0 A1 0 1 2 0 0 4 6 1 5 0 2 2 3 7 0 A2 V0 V2 V1 6 4 3 11 2 A-1 0 0 6 4 3 11 A0 4 6 0 0 7 2 A1 6 3 2 7 0 0 v0 v1 v2
  • 167. CHAPTER 6 167 0 1 4 3 2                 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0                 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 2 3 4 0 1 2 3 4                 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 1 0 1 1 1 1 1 0 1 2 3 4 (a) Digraph G (b) Adjacency matrix A for G (c) transitive closure matrix A+ (d) reflexive transitive closure matrix A* cycle reflexiv e Transitive Closure Goal: given a graph with unweighted edges, determine if there is a path from i to j for all i and j. (1) Require positive path (> 0) lengths. (2) Require nonnegative path (0) lengths. There is a path of length > 0 There is a path of length 0 transitive closure matrix reflexive transitive closure matrix
  • 168. CHAPTER 6 168 Activity on Vertex (AOV) Network definition A directed graph in which the vertices represent tasks or activities and the edges represent precedence relations between tasks. predecessor (successor) vertex i is a predecessor of vertex j iff there is a directed path from i to j. j is a successor of i. partial order a precedence relation which is both transitive (i, j, k, ij & jk => ik ) and irreflexive (x xx). acylic graph a directed graph with no directed cycles
  • 169. CHAPTER 6 169 *Figure 6.38: An AOV network (p.305) Topological order: linear ordering of vertices of a graph i, j if i is a predecessor of j, then i precedes j in the linear ordering C1, C2, C4, C5, C3, C6, C8, C7, C10, C13, C12, C14, C15, C11, C9 C4, C5, C2, C1, C6, C3, C8, C15, C7, C9, C10, C11, C13, C12, C14
  • 170. CHAPTER 6 170 *Program 6.13: Topological sort (p.306) for (i = 0; i <n; i++) { if every vertex has a predecessor { fprintf(stderr, “Network has a cycle. n “ ); exit(1); } pick a vertex v that has no predecessors; output v; delete v and all edges leading out of v from the network; }
  • 171. CHAPTER 6 171 *Figure 6.39:Simulation of Program 6.13 on an AOV network (p.306) v0 no predecessor delete v0->v1, v0->v2, v0->v3 v1, v2, v3 no predecessor select v3 delete v3->v4, v3->v5 select v2 delete v2->v4, v2->v5 select v5 select v1 delete v1->v4
  • 172. CHAPTER 6 172 Issues in Data Structure Consideration Decide whether a vertex has any predecessors. –Each vertex has a count. Decide a vertex together with all its incident edges. –Adjacency list
  • 173. CHAPTER 6 173 *Figure 6.40:Adjacency list representation of Figure 6.30(a) (p.309) 0  1  2  3 NULL 1  4 NULL 1  4  5 NULL 1  5  4 NULL 3 NULL 2 NULL V0 V1 V2 V3 V4 V5 v0 v1 v2 v3 v4 v5 count link headnodes vertex link node
  • 174. CHAPTER 6 174 *(p.307) typedef struct node *node_pointer; typedef struct node { int vertex; node_pointer link; }; typedef struct { int count; node_pointer link; } hdnodes; hdnodes graph[MAX_VERTICES];
  • 175. CHAPTER 6 175 *Program 6.14: Topological sort (p.308) O(n) void topsort (hdnodes graph [] , int n) { int i, j, k, top; node_pointer ptr; /* create a stack of vertices with no predecessors */ top = -1; for (i = 0; i < n; i++) if (!graph[i].count) {no predecessors, stack is linked through graph[i].count = top; count field top = i; } for (i = 0; i < n; i++) if (top == -1) { fprintf(stderr, “n Network has a cycle. Sort terminated. n”); exit(1); }
  • 176. CHAPTER 6 176 O(e) O(e+n) Continued } else { j = top; /* unstack a vertex */ top = graph[top].count; printf(“v%d, “, j); for (ptr = graph [j]. link; ptr ;ptr = ptr ->link ){ /* decrease the count of the successor vertices of j */ k = ptr ->vertex; graph[k].count --; if (!graph[k].count) { /* add vertex k to the stack*/ graph[k].count = top; top = k; } } } }
  • 177. CHAPTER 6 177 Activity on Edge (AOE) Networks directed edge –tasks or activities to be performed vertex –events which signal the completion of certain activities number –time required to perform the activity
  • 178. CHAPTER 6 178 *Figure 6.41:An AOE network(p.310) concurrent
  • 179. CHAPTER 6 179 Application of AOE Network Evaluate performance –minimum amount of time –activity whose duration time should be shortened –… Critical path –a path that has the longest length –minimum time required to complete the project –v0, v1, v4, v7, v8 or v0, v1, v4, v6, v8 (18)
  • 180. CHAPTER 6 180 other factors Earliest time that vi can occur –the length of the longest path from v0 to vi –the earliest start time for all activities leaving vi –early(6) = early(7) = 7 Latest time of activity –the latest time the activity may start without increasing the project duration –late(5)=8, late(7)=7 Critical activity –an activity for which early(i)=late(i) –early(7)=late(7) late(i)-early(i) –measure of how critical an activity is –late(5)-early(5)=8-5=3
  • 181. CHAPTER 6 181 v0 v1 v2 v3 v4 v5 v6 v7 v8 a0=6 a1=4 a2=5 a3=1 a4=1 a5=2 a6=9 a7=7 a9=2 a10=4 a8=4 earliest, early, latest, late 0 0 6 6 7 7 16 16 18 0 4 4 7 14 14 0 5 5 7 7 0 0 6 6 7 7 16 10 18 2 6 6 14 14 14 10 8 8 3
  • 182. CHAPTER 6 182 Determine Critical Paths Delete all noncritical activities Generate all the paths from the start to finish vertex.
  • 183. CHAPTER 6 183 Calculation of Earliest Times vk vl ai early(i)=earliest(k) late(i)=latest(l)-duration of ai earliest[0]=0 earliest[j]=max{earliest[i]+duration of <i,j>} i p(j) earliest[j] –the earliest event occurrence time latest[j] –the latest event occurrence time
  • 184. CHAPTER 6 184 vi1 vi2 vin . . . vj forward stage if (earliest[k] < earliest[j]+ptr->duration) earliest[k]=earliest[j]+ptr->duration
  • 185. CHAPTER 6 185 *Figure 6.42:Computing earliest from topological sort (p.313) v0 v1 v2 v3 v4 v6 v7 v8 v5
  • 186. CHAPTER 6 186 Calculation of Latest Times  latest[j] – the latest event occurrence time latest[n-1]=earliest[n-1] latest[j]=min{latest[i]-duration of <j,i>} i s(j) vi1 vi2 vin . . . vj backward stage if (latest[k] > latest[j]-ptr->duration) latest[k]=latest[j]-ptr->duration
  • 187. CHAPTER 6 187 *Figure 6.43: Computing latest for AOE network of Figure 6.41(a)(p.314)
  • 188. CHAPTER 6 188 *Figure 6.43(continued):Computing latest of AOE network of Figure 6.41(a) (p.315) latest[8]=earliest[8]=18 latest[6]=min{earliest[8] - 2}=16 latest[7]=min{earliest[8] - 4}=14 latest[4]=min{earliest[6] - 9;earliest[7] -7}= 7 latest[1]=min{earliest[4] - 1}=6 latest[2]=min{earliest[4] - 1}=6 latest[5]=min{earliest[7] - 4}=10 latest[3]=min{earliest[5] - 2}=8 latest[0]=min{earliest[1] - 6;earliest[2]- 4; earliest[3] - 5}=0 (c)Computation of latest from Equation (6.4) using a reverse topological order
  • 189. CHAPTER 6 189 *Figure 6.44:Early, late and critical values(p.316) Activity Early Late Late- Early Critical a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 0 0 0 6 4 5 7 7 7 16 14 0 2 3 6 6 8 7 7 10 16 14 0 2 3 0 2 3 0 0 3 0 0 Yes No No Yes No No Yes Yes No Yes Yes
  • 190. CHAPTER 6 190 *Figure 6.45:Graph with noncritical activities deleted (p.316) V0 V4 V8 V1 V6 V7 a0 a3 a6 a7 a10 a9
  • 191. CHAPTER 6 191 *Figure 6.46: AOE network with unreachable activities (p.317) V0 V3 V1 V5 V2 V4 a0 a1 a2 a3 a5 a6 a4 earliest[i]=0
  • 192. CHAPTER 6 192 *Figure 6.47: an AOE network(p.317) V5 V8 V9 a10=5 a13=2 V2 V4 V7 a4=3 a9=4 V1 V3 V6 a2=3 a6=4 V0 a12=4 a11=2 a8=1 a7=4 a5=3 a3=6 a0=5 a1=6 start finish