Basic Search and traversal techniques

57
1 Basic Search and traversal techniques Solution of many problems involve finding vertex of a subset of vertices in a given data objects that satisfies some constraints. We may wish to find all vertices in which a data value is less than x. Determine subset satisfying a given property. Chapter 6: Basic Search and Traversal Techniques 1 Chapter 6: B.S.T.T. When the search is necessarily involves the examination of every vertex being searched, it is called traversal. Binary tree traversal: There are many operations that we want to perform on binary trees- “traversing a tree or visiting each node in the tree exactly once”. Three possible traversals are defined as- 1. Inorder traversal 2. Preorder traversal 3. Postorder traversal 2

Transcript of Basic Search and traversal techniques

1

Basic Search and traversal techniques

Solution of many problems involve finding vertex of a subset

of vertices in a given data objects that satisfies some

constraints.

�We may wish to find all vertices in which a data value

is less than x.

�Determine subset satisfying a given property.

Chapter 6: Basic Search and Traversal Techniques

1

Chapter 6: B.S.T.T.

When the search is necessarily involves the examination of

every vertex being searched, it is called traversal.

Binary tree traversal: There are many operations that we

want to perform on binary trees- “traversing a tree or visiting

each node in the tree exactly once”.

Three possible traversals are defined as-

1. Inorder traversal

2. Preorder traversal

3. Postorder traversal2

2

Graph

• A graph is made up of two parts

• set of nodes, which are commonly called

vertices.

• set of interconnection between the vertices,

called edges.

Chapter 6: B.S.T.T.

3

Graph - Examples

Chapter 6: B.S.T.T.

4

3

Graph - Definition

• A graph G=(V, E) consists of a set of

vertices V, and a set of edges E, such that

each edge in E is a connection between a

pair of vertices in V.

• The number of vertices is written as |V|, and

the number of edges is written as |E|.

Chapter 6: B.S.T.T.

5

Graph - Terminology

• A graph with relatively few edges is called

sparse.

• A graph with many edges is called dense.

• A graph containing all possible edges is called

complete.

Chapter 6: B.S.T.T.

6

4

• A graph whose edges are directed from one vertices to another is called a directed graph or a digraph.

• A graph whose edges are not directed is called an undirected graph.

• A graph with labels associated with its vertices is called a labelled graph.

Chapter 6: B.S.T.T.

7

• Two vertices are adjacent if they are joined by an edge.

Such vertices are also called neighbours.

• An edge connecting vertices v and u is written (v, u).

Such an edge is said to be incident on vertices v and u

• Associated with each edge may be a cost or weight

• Graphs whose edges have weights are called weighted

graphs

Chapter 6: B.S.T.T.

8

5

• A sequence of vertices v1, v2,. . ., vn forms a path

if there exist edges from vi to v i+1 for 1≤ i < n.

• A length of a path is the number of edges it

contains.

Chapter 6: B.S.T.T.

9

• A path is simple if all vertices on the path are

distinct.

• A cycle is a path of length 3 or more that

connects vi to itself.

• A cycle is simple if the path is simple, except for

the first and last vertices being the same.

Chapter 6: B.S.T.T.

10

6

• A graph without cycles is acyclic.

• A directed graph without cycles is a directed

acyclic graph or DAG.

Chapter 6: B.S.T.T.

11

• A subgraph S is the graph formed for graph G by selecting a subset of Vs of G’s vertices and some edges of G, both of whose vertices are in Vs

• An undirected graph is connected if there is at least one path from any vertex to any other

• The maximal connected subgraphs of an undirected graph are called connected components

Chapter 6: B.S.T.T.

12

7

Graph Representations

• There are two commonly used ways for

representing graphs

• Adjacency matrix

• Adjacency list

Chapter 6: B.S.T.T.

13

Adjacency matrix

It is a |V| x |V| array.It

assumes that the vertices

are labelled from v0

through vn-1. Row i of the

array contains entries for

vertex vi. Column j in row

i is marked if there is an

edge from vi to vj, and not

marked otherwise. [If the

graph is weighted array,

cells must store the

weight for each edge]

Cost Θ(|V|2)

Chapter 6: B.S.T.T.

14

8

Adjacency list

It is an array of linkedlists. The array is |V|items long, withposition i storing apointer to the linkedlist of edges for vertexvi

Cost Θ(|V| + |E|)

Chapter 6: B.S.T.T.

15

Chapter 6: B.S.T.T.

Search and traversal techniques for graphs:

Fundamental problem concerning the graph is the path

problem. In its simplest form, it requires us to determine

whether or not there exist a path in a given graph G = (V, E)

such that the path starts at vertex v and ends at vertex u.

More general form would be to determine for a given

starting vertex all vertices u such that there is a path from

v to u.

16

9

Chapter 6: B.S.T.T.

Breadth First Search (BFS)

In BFS we start at vertex v and make it as having been

reached (visited). The vertex v will at this time should be

unexplored.

A vertex will be said to have been explored by an algorithm

when the algorithm has visited all the vertices adjacent from it.

All the unvisited vertices adjacent from v are visited next.

17

• Breadth–first search tries to stay as close as

possible to the starting point. It first visits the

vertices adjacent to the starting vertex, and only

then it goes farther away.

• It uses a to store nodes

Chapter 6: B.S.T.T.

queue

18

10

• The rules• Rule 1:

» If possible, visit an adjacent unvisited vertex, mark it, and insert it into the queue

• Rule 2:

» If you can not follow Rule 1, then, if possible, remove a vertex from a queue and make it the current (explored) vertex

• Rule 3:

» If you cannot carry out Rule 2 because the queue is empty, you’re finished

Chapter 6: B.S.T.T.

19

Chapter 6: B.S.T.T.

Tracing Breadth First

1

4 5 6 7

2 3

8

20

11

Chapter 6: B.S.T.T.

Current vertex Unvisited neighbour Queue(tail head)

1 2, 3 [3, 2]2 4, 5 [5, 4, 3]3 6, 7 [7, 6, 5, 4]4 8 [8, 7, 6, 5]5 none [8, 7, 6]6 none [8, 7]7 none [8]8 none [queue empty]

Tracing Breadth First

1

4 5 6 7

2 3

8

21

Chapter 6: B.S.T.T.

Global G : Graph;

visited Array[vertices] of boolean;

procedure BFS(v: vertex);

//algorithm starts at vertex v, all visited vertices are marked as

VISITED[i] := true;//

var : u, v :verices;

Q: queue of vertices;

begin

1.VISITED[v] := true; u:= v;

initialize Q to be empty queue //queue of unexplored

vertices//22

12

Chapter 6: B.S.T.T.

repeat

for all vertices w adjacent from u do

begin

if (not VISITED[w]) then

begin

ADDQ(w, Q); {w is unexplored}

6. VISITED[w] := true;

end;

if Q is not empty then DELETE(u, Q);

until Q is not empty

end.23

Breadth–first search – Example

GG II

FF

DD

CC

BB

AA

HH

EEQueueQueue

Chapter 6: B.S.T.T.

24

13

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘A’Visit ‘A’

QueueQueue

Chapter 6: B.S.T.T.

25

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘B’Visit ‘B’

QueueQueue

BB

Chapter 6: B.S.T.T.

26

14

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘C’Visit ‘C’

QueueQueue

BB CC

Chapter 6: B.S.T.T.

27

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘D’Visit ‘D’

QueueQueue

BB CC DD

Chapter 6: B.S.T.T.

28

15

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘E’Visit ‘E’

QueueQueue

BB CC DD EE

Chapter 6: B.S.T.T.

29

GG II

FF

DD

CC

BB

AA

HH

EE

Dequeue ‘B’Dequeue ‘B’

QueueQueue

CC DD EE

Chapter 6: B.S.T.T.

30

16

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘F’Visit ‘F’

QueueQueue

CC DD EE FF

Chapter 6: B.S.T.T.

31

GG II

FF

DD

CC

BB

AA

HH

EE

Dequeue ‘C’Dequeue ‘C’

QueueQueue

DD EE FF

Chapter 6: B.S.T.T.

32

17

GG II

FF

DD

CC

BB

AA

HH

EE

Dequeue ‘D’Dequeue ‘D’

QueueQueue

EE FF

Chapter 6: B.S.T.T.

33

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘G’Visit ‘G’

QueueQueue

EE FF GG

Chapter 6: B.S.T.T.

34

18

GG II

FF

DD

CC

BB

AA

HH

EE

Dequeue ‘E’Dequeue ‘E’

QueueQueue

FF GG

Chapter 6: B.S.T.T.

35

GG II

FF

DD

CC

BB

AA

HH

EE

Dequeue ‘F’Dequeue ‘F’

QueueQueue

GG

Chapter 6: B.S.T.T.

36

19

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘H’Visit ‘H’

QueueQueue

GG HH

Chapter 6: B.S.T.T.

37

GG II

FF

DD

CC

BB

AA

HH

EE

Dequeue ‘G’Dequeue ‘G’

QueueQueue

HH

Chapter 6: B.S.T.T.

38

20

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘I’Visit ‘I’

QueueQueue

HH II

Chapter 6: B.S.T.T.

39

GG II

FF

DD

CC

BB

AA

HH

EE

Dequeue ‘H’Dequeue ‘H’

QueueQueue

II

Chapter 6: B.S.T.T.

40

21

GG II

FF

DD

CC

BB

AA

HH

EE

Dequeue ‘I’Dequeue ‘I’

QueueQueue

Chapter 6: B.S.T.T.

41

GG II

FF

DD

CC

BB

AA

HH

EE

DoneDone

QueueQueue

Chapter 6: B.S.T.T.

42

22

Chapter 6: B.S.T.T.

Theorem: Let t(n,e) and s(n,e) be the maximum time and

maximum additional space taken by algorithm BFS on any

graph G with n vertices and e edges.

t(n,e) = Θ(n+e) and s(n,e) = Θ(n) if G is represented by

adjacency lists.

If G is represented by its adjacency matrix then t(n,e) = Θ(n2)

and s(n,e) = Θ(n).

If BFS is used on a connected graphs then all vertices in G get

visited and graph is traversed. However if graph is not

connected then at least one vertex of G is not visited.

43

Chapter 6: B.S.T.T.

A complete traversal of graph can be made by repeatedly

calling BFS. The resulting traversal algorithm is Breadth First

Traversal.

procedure BFT(G: graph; n:integer);

var visited : array[1..n] of boolean;

begin

for i := 1 to n do

visited[i] := false;

for i := 1 to n do

if not visited[i] then BFS(i);

end. 44

23

Chapter 6: B.S.T.T.

If G is a connected undirected graph then all vertices of G

will get visited on the first call of BFS. If G is not connected

then at least two calls to BFS are needed.

Applications of BFS

• Graph is connected or not?

• All newly visited vertices of BFS from BFT

represent the vertices in a connected component in

G. BFS can be modified so that newly visited

vertices are put into list.

45

Chapter 6: B.S.T.T.

• Minimum spanning tree: Consider set of edges (u, w)

used in BFS to reach unvisited vertices w. These vertices

are called forward edges. If T denotes the set then it is a

spanning tree of G. T will be having all edges except (5,

8), (6, 8) and (7, 8).

Ex. Modify algorithm BFS by adding statements T := ∅ and

to line 1 and 6 to get BFS minimum spanning

tree.

)},{( wuTT U=

46

24

Chapter 6: B.S.T.T.

BFS Spanning Tree

1

4 5 6 7

2 3

8

47

Chapter 6: B.S.T.T.

Depth First Search (DFS)

A depth first search of a graph differs from a BFS in that the

exploration of a vertex v is suspended as soon as a new vertex

is reached.

At this time the exploration of the new vertex u begins. When

the exploration of the new vertex completes we continue to

explore v. The search terminates when all reached vertices are

fully explored.

48

25

Chapter 6: B.S.T.T.

1

2

3

4

8

7

6

5

2

1

1

2

2

3

3

4

3

4

6

8

8

8

8

5

5

7

6 7Undirected Graph

Adjacency List for Graph

1

4 5 6 7

2 3

8

1

2

4

8

5 6

3

7

49

Chapter 6: B.S.T.T.

Global G : Graph of vertices;

visited Array[vertices] of boolean;

procedure DFS(v: vertex);

//algorithm starts at vertex v, initially all vertices are marked as VISITED[n] := false;//

var : w :verices;

begin

1. VISITED[v] := true;

2. for all vertices w adjacent from v do

3. if (not VISITED[w]) then DFS(w);

end. 50

26

Chapter 6: B.S.T.T.

Nodes are visited in the order 1, 2, 4, 8, 5, 6, 3, 7

51

• The rules

• Rule 1:

» If possible, visit an adjacent unvisited

vertex, mark it, and push it on the stack

• Rule 2:

» If you can not follow Rule 1, then, if

possible, pop a vertex off the stack

• Rule 3:

» If you cannot follow Rule 1 or Rule 2,

you’re finished

Chapter 6: B.S.T.T.

52

27

Depth–first search – Example

GG II

FF

DD

CC

BB

AA

HH

EE StackStack

Chapter 6: B.S.T.T.

53

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘A’Visit ‘A’

StackStack

AA

Chapter 6: B.S.T.T.

54

28

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘B’Visit ‘B’

StackStack

AA

BB

Chapter 6: B.S.T.T.

55

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘F’Visit ‘F’

StackStack

AA

BB

FF

Chapter 6: B.S.T.T.

56

29

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘H’Visit ‘H’

StackStack

AA

BB

FF

HH

Chapter 6: B.S.T.T.

57

GG II

FF

DD

CC

BB

AA

HH

EE

Pop ‘H’Pop ‘H’

StackStack

AA

BB

FF

Chapter 6: B.S.T.T.

58

30

GG II

FF

DD

CC

BB

AA

HH

EE

Pop ‘F’Pop ‘F’

StackStack

AA

BB

Chapter 6: B.S.T.T.

59

GG II

FF

DD

CC

BB

AA

HH

EE

Pop ‘B’Pop ‘B’

StackStack

AA

Chapter 6: B.S.T.T.

60

31

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘C’Visit ‘C’

StackStack

AA

CC

Chapter 6: B.S.T.T.

61

GG II

FF

DD

CC

BB

AA

HH

EE

Pop ‘C’Pop ‘C’

StackStack

AA

Chapter 6: B.S.T.T.

62

32

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘D’Visit ‘D’

StackStack

AA

DD

Chapter 6: B.S.T.T.

63

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘G’Visit ‘G’

StackStack

AA

DD

GG

Chapter 6: B.S.T.T.

64

33

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘I’Visit ‘I’

StackStack

AA

DD

GG

II

Chapter 6: B.S.T.T.

65

GG II

FF

DD

CC

BB

AA

HH

EE

Pop ‘I’Pop ‘I’

StackStack

AA

DD

GG

Chapter 6: B.S.T.T.

66

34

GG II

FF

DD

CC

BB

AA

HH

EE

Pop ‘G’Pop ‘G’

StackStack

AA

DD

Chapter 6: B.S.T.T.

67

GG II

FF

DD

CC

BB

AA

HH

EE

Pop ‘D’Pop ‘D’

StackStack

AA

Chapter 6: B.S.T.T.

68

35

GG II

FF

DD

CC

BB

AA

HH

EE

Visit ‘E’Visit ‘E’

StackStack

AA

EE

Chapter 6: B.S.T.T.

69

GG II

FF

DD

CC

BB

AA

HH

EE

Pop ‘E’Pop ‘E’

StackStack

AA

Chapter 6: B.S.T.T.

70

36

GG II

FF

DD

CC

BB

AA

HH

EE

Pop ‘A’Pop ‘A’

StackStack

Chapter 6: B.S.T.T.

71

GG II

FF

DD

CC

BB

AA

HH

EE

DoneDone

StackStack

Chapter 6: B.S.T.T.

72

37

EE

DD

CC

BB

AA

EE

DD

CC

BB

AA

DFSDFS

Chapter 6: B.S.T.T.

Spanning tree generated by DFS is known as depth first

spanning tree.

73

Chapter 6: B.S.T.T.

DFS Spanning Tree

1

4 5 6 7

2 3

8

74

38

Chapter 6: B.S.T.T.

D-Search: Differs from BFS only in that the next node to

explore is the most recently reached unexplored node.

75

Chapter 6: B.S.T.T.

Code Optimization

Function of compiler

This translation will depends on the particular assembly

language and machine being used.

Machine model A, with one register “accumulator”, all the

arithmetic are to be performed in this register. � represents a

binary operator for +, -, *, /. Left operand should always be in

accumulator.

We shall be looking into a problem of

translating arithmetic expression into assembly language code.

?

76

39

Chapter 6: B.S.T.T.

Assembly language instructions are-

LOAD X load accumulator with the contents of

memory location.

STORE X store contents of accumulator into

memory location X.

OP X OP may be ADD, SUB, MPY or DIV

The instruction OP X computes the operator OP using the

contents of the accumulator as a left operand and that of

memory location X as the right operand.

77

Chapter 6: B.S.T.T.

Consider the expression (a+b)/(c+d)

LOAD a

ADD b

STORE T1

LOAD c

ADD d

STORE T2

LOAD T1

DIV T2

LOAD c

ADD d

STORE T1

LOAD a

ADD b

DIV T1

78

40

Chapter 6: B.S.T.T.

Definition: Translation of the expression E into the machine

or assembly language is optimal iff it has a minimum number

of instructions.

Ex. Possible code for a+b*c

LOAD b

MPY c

STORE T1

LOAD a

ADD T1

LOAD b

MPY c

ADD a

79

Chapter 6: B.S.T.T.

Definition: A binary operator is commutative in the domain

D iff a � b = b � a, for all a, b ∈∈∈∈ D.

Ex. Code for a*b + c*b with the commutative property is-

LOAD c

MPY b

STORE T1

LOAD a

MPY b

ADD T1

LOAD a

ADD c

MPY b

80

41

Chapter 6: B.S.T.T.

Definition: A binary operator ⊗⊗⊗⊗ is left associative with

respect to the binary operator ⊕⊕⊕⊕ over the domain D iff

a ⊗⊗⊗⊗ (b ⊕⊕⊕⊕ c) = (a ⊗⊗⊗⊗ b) ⊕⊕⊕⊕ (a ⊗⊗⊗⊗ c) and right associative

w.r.t the binary operator ⊕⊕⊕⊕ over the domain D iff, for all

a, b, c ∈∈∈∈ D, (a ⊕⊕⊕⊕ b) ⊗⊗⊗⊗ c = (a ⊗⊗⊗⊗ c) ⊕⊕⊕⊕ (b ⊗⊗⊗⊗ c).

81

Chapter 6: B.S.T.T.

Ex. Code for a*(b*c)+d*c = (a*b)*c+d*c = ((a*b)+d)*c

LOAD b

MPY c

STORE T1

LOAD a

MPY T1

STORE T1

LOAD d

MPY c

STORE T2

LOAD T1

ADD T2

LOAD a

MPY b

ADD d

MPY c

82

42

Chapter 6: B.S.T.T.

Definition: A binary operator � is associative over the

domain D iff a �(b � c) = (a � b) � c, for all a, b, c ∈∈∈∈ D.

Having seen that different codes are possible for a given

expression (in infix form), we find the way for the optimal

code.

We express the expression as the binary tree, where non leaf

nodes represent operator and leaf nodes represents constant or

variable.83

Chapter 6: B.S.T.T.

Expression Tree

tree for (a+b)/(c*d)

+

/

*

a b c d

84

43

Chapter 6: B.S.T.T.

To begin with, we assume that none of the operators are

commutative, associative or distributive, along with any

possibility of algebraic simplification.

Under the assumption, it is easy to see that if the expression

has n operators then the code will have exactly n instructions

of type ADD, SUB, MPY, DIV, called operator instructions,

only the number of LOAD or STORE will vary.

By examining the code it can be seen that each load instruction

except the first must be preceded immediately by a store

instruction. Number of loads is always one more than the

number of stores. 85

Chapter 6: B.S.T.T.

It is sufficient to generate a code in which we can reduce

number of LOADS or STORES.

Let P denotes the internal node of any expression tree and L

and R be its left and right subtrees. Let � be any operator at

node P.

86

44

Chapter 6: B.S.T.T.

Let CL and CR denotes optimal code for expression tree L and

R respectively. To compute L � R we have several

possibilities.

The only way to compute L � R is to compute L and R

independently and then compute L � R. The code for L and R

must also be optimal. Once we have optimal code for L and R,

several possibilities exist for L � R.

87

Chapter 6: B.S.T.T.

1. both L and R are leaves LOAD a; � b

2. L is leaf variable a; CR; STORE T1; LOAD a � T1

R is not leaf

3. R is leaf with a; L is not leaf CL; � a

4. L and R both not leaf and L is CL; STORE T1; CR;

computed before R STORE T2; LOAD T1; � T2

5. L and R both not leaf and R is CR; STORE T1; CL; � T1

computed before L 88

45

Chapter 6: B.S.T.T.

procedure CODE1(T);

//code generation for tree T assuming that T ≠ 0//

Begin //1//

if T is a leaf then print(“LOAD”, DATA(T)); return;

F := 0; //F is set to 1 if RCHILD(T) is not a leaf//

if RCHILD(T) is not a leaf then

begin //2//

CODE1(RCHILD(T)); //generate CR//

TEMP(i);

print(“STORE”, i);89

Chapter 6: B.S.T.T.

F:= 1;

end;//2//

CODE1(LCHILD(T));

if (F = 1) then

begin//3//

print(DATA(T), i);

RETEMP(i);

end//3//

else

print(DATA(T), DATA(RCHILD(T));

end.//1// 90

46

Chapter 6: B.S.T.T.

We generalize the machine A to another machine B, which has

N ≥ 1 registers in which the arithmetic can be performed.

Four types of machine instructions are-

1. LOAD M, R (M � R) 2. STORE M, R (R � M)

3. OP R1, M, R2 4. OP R1, R2, R3

91

Chapter 6: B.S.T.T.

Optimal codes for E = ((a+b) /(c*d)) with N = 1 and N = 2 are

LOAD c, R1

MPY R1, d, R1

LOAD a, R2

ADD R2, b, R2

DIV R2, R1, R1

LOAD c, R1

MPY R1, d, R1

STORE T1, R1

LOAD a, R1

ADD R1, b, R1

DIV R1, T1, R1

N = 1 N = 292

47

Chapter 6: B.S.T.T.

Can E be evaluated without stores?

Assume that value of E is to be stored in one of the N registers

and represented by tree T. If T has one node then the value of

variable or constant is to be loaded in register and one register

is needed.

What is the minimum

number of registers needed to evaluate E without any store?

93

Chapter 6: B.S.T.T.

tree T optimal code1. no operator

LOAD a, R1

2. only one operator LOAD a, R1.

ba R1, b, R1

3. more than one operator

.l1

l2

a

.

a b

.

L R

94

48

Chapter 6: B.S.T.T.

Let l1 and l2 denotes the minimum number of registers required

to independently evaluate L and R operands. Let l be the

minimum number of registers needed to compute L�R, then

l ≥ max(l1, l2 ).

If l1 > l2 then solve L with l1 and store result to any one of

register and compute R with l1 -1 ≥ l2 registers. Hence when

l1 > l2 , l = l1. When l1 < l2 then l = l2

95

Chapter 6: B.S.T.T.

When l1 = l2, we have two possibilities.

1. R is leaf then l = l1, compute L using l1 registers and

then use instruction type (3) to compute L � R,

placing the result in any one of the l1 registers.

2. l = l1+1, this is needed to store the value of the

operand, which has been evaluated first.

1. LOAD M, R (M � R) 2. STORE M, R (R � M)

3. OP R1, M, R2 4. OP R1, R2, R3

96

49

Chapter 6: B.S.T.T.

Theorem: Let P be a node in an expression tree T of depth at

least 2. Define a function MR(P) (minimum registers) as

follows.

+

=

1

},max{

1

0

)(

1

21

l

llPMR

If P is a leaf and right child of its parent

If P is a leaf and left child of its parent

Where l1 = MR(LCHILD(P));l2 = MR(RCHILD(P)) and l1 ≠≠≠≠ l2

If l1 l2, as above and l1 = l2

97

Chapter 6: B.S.T.T.

Example with the formula

/ *

b c e f

a + d +

+

1 0

11

2

1 0

11

2

(a/(b+c)) + d*(e+f) 3+

/ *

a d+ +

b c e f

98

50

Chapter 6: B.S.T.T.

If N registers are available with MR ≤ N then T can be

evaluated without any STORE. Then the optimal code has to

minimize only the number of LOAD’s

99

Chapter 6: B.S.T.T.

The algorithm assumes that each node in the expression

tree T has four fields: LCHILD, RCHILD, DATA and MR.

The MR values have been computed as discussed in the

last class. CODE2 uses a subroutine TEMP. CODE2 is

called as call CODE2 (T,1). N is global variable.

100

51

Chapter 6: B.S.T.T.

procedure CODE2(T,i);

//generates code for machine B with N registers using registers R1...RN only. Result is left in Ri//

begin

if T is a leaf then //left child of parent//

print(‘LOAD’, DATA(T), ‘R’, i); return;

//T is an internal node//

L:= LCHILD(T); R:= RCHILD(T);

case

:MR(R) = 0: //R is a leaf//

begin

101

Chapter 6: B.S.T.T.

CODE2(L,i); print(DATA(T), ‘R’, i,’,’,DATA(R),’,R’,i);

end;

:MR(L) ≥ N and MR(R) ≥ N;

begin

CODE2(R, i); TEMP(S);

print(‘STORE’, ‘R’, i, ‘, ‘, S); CODE2(L, i);

print(DATA(T), ‘R’, i, ‘, ‘, S,’,R’,i); RETEMP(S);

end;

:MR(L) < MR(R):

begin

CODE2(R,i); CODE2(L, i+1);

print(DATA(T), ‘,R’, i+1, ‘, R’,i,’, R’,i); 102

52

Chapter 6: B.S.T.T.

:else: //evaluate L first//

begin

CODE2(L,i);

CODE2(R, i+1);

print(DATA(T), ‘,R’, i, ‘, R’,i+1, ‘,R’,i);

end;

end.

103

Chapter 6: B.S.T.T.

Expression Tree

tree for a +(b*c)

a

+

*

b c

1

2

1

1 0

104

53

Chapter 6: B.S.T.T.

LOAD a, R1

LOAD b, R2

MPY R2, c, R2

ADD R1, R2, R1

N = 2

E = a +(b*c)

105

Chapter 6: B.S.T.T.

LOAD d, R1

LOAD e, R2

ADD R2, f, R2

MPY R1, R2, R1

STORE T1, R1

LOAD a, R1

LOAD b, R2

ADD R2, c, R2

DIV R1, R2, R1

ADD R1, T1, R1

N = 2

LOAD a, R1

LOAD b, R2

ADD R2, c, R2

DIV R1, R2, R1

LOAD d, R2

LOAD e, R3

ADD R3, f, R3

MPY R2, R3, R2

ADD R1, R2, R1

N = 3

E = (a/(b+c)) + d*(e+f)

106

54

107

DAGs and Topological Ordering• A directed acyclic graph

(DAG) is a digraph that

has no directed cycles

• A topological ordering

of a digraph is a

numbering

v1 , …, vn

of the vertices such that

for every edge (vi , vj),

we have i < j

B

A

D

C

E

DAG G

B

A

D

C

E

v1

v2

v3

v4 v5

Chapter 6: B.S.T.T.

108

DAGs and Topological Ordering• Example: in a task

scheduling digraph, a

topological ordering a

task sequence that

satisfies the precedence

constraints

Theorem

A digraph admits a

topological ordering if

and only if it is a DAG

B

A

D

C

E

DAG G

B

A

D

C

E

Topological ordering of G

v1

v2

v3

v4 v5

Chapter 6: B.S.T.T.

55

109

Meet and do fun

play

Topological Sorting• Number vertices, so that (u,v) in E implies index (u) <

index(v)

work out

sleep

dream about jobs

A typical student daywake up

1

study computer sci.

2eat

3

nap4

more c.s.

5

6

7

8

9

10

11

Dinner

Chapter 6: B.S.T.T.

110

Algorithm for Topological Sorting

Method TopologicalSort(G)

H ← G // Temporary copy of G

n ← G.numVertices()

while H is not empty do

Let v be a vertex with no outgoing edges

Label v ← n

n ← n - 1

Remove v from H

Chapter 6: B.S.T.T.

56

111

Topological Sorting Algorithm using DFSL ← Empty list that will contain the sorted nodes

while there are unmarked nodes do

select an unmarked node n

visit(n)

function visit(node n)

if n has a temporary mark then stop (not a DAG)

if n is not marked (i.e. has not been visited yet) then

mark n temporarily

for each node m with an edge from n to m do

visit(m)

mark n permanently

unmark n temporarily

add n to head of L

Chapter 6: B.S.T.T.

Demo

DFS Topological Sorting

• Each node n gets prepended to the output

list L only after considering all other nodes

on which n depends (all ancestral nodes

of n in the graph).

112

Chapter 6: B.S.T.T.

57

DFS Topological Sorting

• Specifically, when the algorithm adds

node n, we are guaranteed that all nodes on

which n depends are already in the output

list L: they were added to L

– either by the preceding recursive call to visit(),

or

– by an earlier call to visit().

• Since each edge and node is visited once,

the algorithm runs in linear time.

113

Chapter 6: B.S.T.T.

End of Chapter 6

Chapter 6: B.S.T.T.

114