5 Discrete Mathematics
5 Discrete Mathematics
(Computer Science)
SEMESTER - I (CBCS)
DISCRETE MATHEMATICS
Unit - I
1. Recurrence Relations - Functions 01
2. Recurrence Relations - Relations 06
3. Recurrence Relations 13
Unit- II
5. Counting Principles 28
Unit - III
7. Graphs 47
8. Trees 70
Syllabus
F.Y.B.Sc. (CS) Discrete Mathematics
Semester I (CBCS)
Objectives:
The purpose of the course is to familiarize the prospective learners
with mathematical structures that are fundamentally discrete. This course
introduces sets and functions, forming and solving recurrence relations
and different counting principles. These concepts are useful to study or
describe objects or problems in computer algorithms and programming
languages.
Unit I :
Recurrence Relations
(a) Functions: Definition of function. Domain, co domain and the range of
a function. Direct and inverse images. Injective, surjective and bijective
functions. Composite and inverse functions.
(b) Relations: Definition and examples. Properties of relations , Partial
Ordering sets, Linear Ordering Hasse Daigrams, Maximum and Minimum
elements, Lattices
(c) Recurrence Relations: Definition of recurrence relations, Formulating
recurrence relations, solving recurrence relations- Back tracking method,
Linear homogeneous recurrence relations with constant coefficients.
Solving linear homogeneous recurrence relations with constant
coefficients of degree two when characteristic equation has distinct roots
and only one root, Particular solutions of non linear homogeneous
recurrence relation, Solution of recurrence relation by the method of
generation functions, Applications- Formulate and solve recurrence
relation for Fibonacci numbers, Tower of Hanoi, Intersection of lines in a
plane, Sorting Algorithms.
Unit II
Counting Principles, Languages and Finite State Machine
(a) Permutations and Combinations: Partition and Distribution of objects,
Permutation with distinct and indistinct objects, Binomial numbers,
Combination with identities : Pascal Identity, Vandermonde’s Identity,
Pascal triangle, Binomial theorem, Combination with indistinct objects.
(b) Counting Principles: Sum and Product Rules, Two-way counting, Tree
diagram for solving counting problems, Pigeonhole Principle (without
I
proof); Simple examples, Inclusion Exclusion Principle (Sieve formula)
(Without proof).
(c) Languages, Grammars and Machines: Languages, regular Expression
and Regular languages, Finite state Automata, grammars, Finite state
machines, Gödel numbers, Turing machines.
Unit III
Graphs and Trees
(a) Graphs : Definition and elementary results, Adjacency matrix, path
matrix, Representing relations using diagraphs, Warshall’s algorithm -
shortest path, Linked representation of a graph, Operations on graph with
algorithms - searching in a graph; Insertion in a graph, Deleting from a
graph, Traversing a graph- Breadth-First search and Depth-First search.
(b) Trees: Definition and elementary results. Ordered rooted tree, Binary
trees, Complete and extended binary trees, representing binary trees in
memory, traversing binary trees, binary search tree, Algorithms for
searching and inserting in binary search trees, Algorithms for deleting in a
binary search tree
Text books:
1. Discrete Mathematics and Its Applications, Seventh Edition by
Kenneth H. Rosen, McGraw Hill Education (India) Private Limited.
(2011)
2. Norman L. Biggs, Discrete Mathematics, Revised Edition, Clarendon
Press, Oxford 1989.
3. Data Structure Seymor Lipschutz, Schaum’s out lines, McGraw-Hill
Inc.
Additional References:
1. Elements of Discrete Mathematics: C.L. Liu , Tata McGraw- Hill
Edition .
2. Concrete Mathematics (Foundation for Computer Science): Graham,
Knuth, Patashnik Second Edition, Pearson Education.
3. Discrete Mathematics : Semyour Lipschutz, Marc Lipson, Schaum’s
out lines, McGraw - Hill Inc.
4. Foundations in Discrete Mathematics: K.D. Joshi, New Age
Publication, New Delhi.
II
Unit I
Recurrence Relations
1
FUNCTIONS
Unit Structure:
1.1 Introduction.
1.2 Functions.
1.3 Domain, Co-domain and the range of a function.
1.4 Injective, surjective and bijective functions.
1.5 Composite and inverse functions
1.5 Summary
1.6 Exercise
1.7 Reference.
1.1 INTRODUCTION
1.2 FUNCTIONS
e.g. f(x) = x2 shows us that function "f" takes "x" and squares it. Here f
stands for function; x stands for input; x2 stands for output.
f(x) = x2
1
Function Input Output
1 1
2
2
3
3 4
5
4 6
A B
7
8
9
2
In above example A = {1, 2, 3, 4 } is domain , B = {1,2,3,4,5,6,7,8,9} is a
co-domain and Range = {3, 5, 7, 9}
Range is calculated in following manner:
f(x) = 2x + 1 …. For x =1 …… f(1) = 2 (1) + 1= 2 + 1 = 3
f(x) = 2x + 1 …. For x =2 …… f(1) = 2 (2) + 1= 4 + 1 = 5
f(x) = 2x + 1 …. For x =3 …… f(1) = 2 (3) + 1= 6 + 1 = 7
f(x) = 2x + 1 …. For x =4 …… f(1) = 2 (4) + 1= 8 + 1 = 9
Injective
A function f is injective if and only if whenever f(x) = f(y), x = y.
Example: f(x) = x+5 from the set of real numbers real numbers to real
numbers is an injective function.
Is it true that whenever f(x) = f(y), x = y ?
Imagine x=3, then:
f(x) = 8
Now I say that f(y) = 8, what is the value of y? It can only be 3, so x=y
Surjective
A function f (from set A to B) is surjective if and only if for every
y in B, there is at least one x in A such that f(x) = y, in other words f is
surjective if and only if f(A) = B.
In simple terms: every B has some A.
Example: The function f(x) = 2x from the set of natural numbers to the set
of non-negative even numbers is a surjective function.
BUT f(x) = 2x from the set of natural numbers to natural numbers is not
surjective, because, for example, no member in natural numbers can be
mapped to 3 by this function.
Bijective
A function f (from set A to B) is bijective if, for every y in B, there is
exactly one x in A such that f(x) = y
Alternatively, f is bijective if it is a one-to-one correspondence between
those sets, in other words both injective and surjective.
Example: The function f(x) = x2 from the set of positive real numbers to
positive real numbers is both injective and surjective. Thus it is also
bijective.
But the same function from the set of all real numbers real
numbers is not bijective because we could have, for example, both
f(2)=4 andf(-2)=4
3
1.5 COMPOSITE AND INVERSE FUNCTIONS
(f∘g)(x) =f(g(x))
2.5 SUMMARY
2.7 REFERENCES:-
5
2
RELATIONS
Unit Structure: -
2.1 Introduction.
2.2 Definition and Examples
2.3 Properties of Relations
2.4 Partial Ordering Set.
2.5 Hasse Diagram.
2.6 Maximum and Minimum Element
2.7 Summary
2.8 Exercise
2.9 Reference.
2.1 INTRODUCTION
For example : Let A = {1, 2} and B = {a, b}. Then {(1, a), (1,b), (2, b)} is
a relation from A to B.
Many edges in the directed graph for a finite poset do not have to
be shown because they must be present. For instance, consider the directed
graph for the partial ordering {(a, b) | a ≤ b} on the set {1, 2, 3, 4}, shown
in Figure 1(a).
Because this relation is a partial ordering, it is reflexive, and its
directed graph has loops at all vertices. Consequently, we do not have to
show these loops because they must be present; in Figure 1(b) loops are
not shown. Because a partial ordering is transitive, we do not have to show
those edges that must be present because of transitivity.
For example, in Figure 1(c) the edges (1, 3), (1, 4), and (2, 4) are
not shown because they must be present. If we assume that all edges are
pointed “upward” (as they are drawn in the figure), we do not have to
show the directions of the edges; Figure 2(c) does not show directions. In
general, we can represent a finite poset (S, ) using this procedure: Start
with the directed graph for this relation. Because a partial ordering is
reflexive, a loop (a, a) is present at every vertex a.
1. Remove these loops.
2. Next, remove all edges that must be in the partial ordering because of
the presence of other edges and transitivity. That is, remove all edges
(x, y) for which there is an element z ∈ S such that x ≺ z and z ≺ x.
3. Finally, arrange each edge so thatits initial vertex is below its terminal
vertex (as it is drawn on paper).
4. Remove all the arrows on the directed edges, because all edges point
“upward” toward their terminal vertex.
These steps are well defined, and only a finite number of steps
need to be carried out for a finite poset. When all the steps have been
taken, the resulting diagram contains sufficient information to find the
partial ordering, as we will explain later. The resulting diagram is called
theHasse diagram of poset named after the twentieth-century German
mathematician Helmut Hasse who made extensive use of them. Let (S, ≺)
8
be a poset. We say that an element y ∈ S covers an element x ∈ S if x ≺y
and there is no element z ∈ S such that x ≺ z ≺ y. The set of pairs (x, y)
such that y covers x is called the covering relation of (S,≺ ). From the
description of the Hasse diagram of a poset, we see that the edges in the
Hasse diagram of (S,≺ ) are upwardly pointing edges corresponding to the
pairs in the covering relation of (S,≺ ). Furthermore, we can recover a
poset from its covering relation, because it is the reflexive transitive
closure of its covering relation. (Exercise 31 asks for a proof of this fact.)
This tells us that we can construct a partial ordering from its Hasse
diagram.
Figure 1
Solution: Begin with the digraph for this partial order, as shown in Figure
3(a). Remove all loops, as shown in Figure 3(b). Then delete all the edges
implied by the transitive property. These are (1, 4), (1, 6), (1, 8), (1, 12),
(2, 8), (2, 12), and (3, 12). Arrange all edges to point upward, and delete
all arrows to obtain the Hasse diagram. The resulting Hasse diagram is
shown in Figure 3(c).
Figure 2
9
2.6 MAXIMUM AND MINIMUM ELEMENTS
EXAMPLE 1 : Which elements of the poset ({2, 4, 5, 10, 12, 20, 25}, |)
are maximal, and which are minimal? Solution: The Hasse diagram in
Figure 2 for this poset shows that the maximal elements are 12, 20, and
25, and the minimal elements are 2 and 5. As this example shows, a poset
can have more than one maximal element and more than one minimal
element. Sometimes there is an element in a poset that is greater than
every other element. Such an element is called the greatest element. That
is, a is the greatest element of the poset (S, ≺)
Lattices
Figure 3
10
2.7 SUMMARY
2.8 EXERCISE
11
a) a is taller than b.
b) a and b were born on the same day.
c) a has the same first name as b.
d) a and b have a common grandparent.
2.9 REFERENCES
12
3
RECURRENCE RELATION
Unit Structure: -
3.1 Introduction,
3.2 Definition and Formulation
3.3 Solving Recurrence Relation
3.3.1 Backtracking
3.3.2 Linear homogeneous recurrence relations with constant
coefficients.
3.3.3 Non Linear Recurrence Relations with Constant
Coefficients.
3.3.4 Generating Functions
3.4 Summary
3.5 Exercise
3.6 References
3.1 INTRODUCTION
13
These are some examples of linear recurrence equations
3.3.1BACKTRACKING
14
3.3.2 LINEAR HOMOGENEOUS RECURRENCE RELATIONS
WITH CONSTANT COEFFICIENTS
15
Example The Fibonacci sequence fn= fn−1 + fn−2 is a homogeneous
relation. Let us compute its characteristic equation:
xn − xn−1 − xn−2 = 0 ⇐⇒ xn−2
(x2 − x − 1) = 0
therefore x2 − x − 1 = 0 is the characteristic equation.
Let us focus on quadratic characteristic equations, that is of the formx2 −
c1x − c2 = 0which corresponds to linear recurrences of the form
an = c1an−1 + c2an−2.
Suppose that x2 − c1x − c2 = 0 has two distinct real roots s1, s2, then
s21 − c1s1 − c2 = 0, s22 − c1s2 − c2 = 0.
Thereforesn1 − c1sn−11 − c2sn−2 = 0, sn2 − c1sn−12 − c2sn−2 = 0
and we have that if s is a solution of x2 −c1x−c2 = 0 then snis a solution
ofan = c1an−1+c2an−2. This tells us that solutions of an are composed of
sn1, sn2.
Example :
Solve the recurrence relation Fn=5Fn−1−6Fn−2 where F0=1 and F1=4
Solution
The characteristic equation of the recurrence relation is −
x2−5x+6=0,
So, (x−3)(x−2)=0
Hence, the roots are −
x1=3 and x2=2
The roots are real and distinct. So, this is in the form of case 1
Hence, the solution is −
Fn=axn1+bxn2
Here, Fn=a3n+b2n (As x1=3 and x2=2)
Therefore,
1=F0=a30+b20=a+b
4=F1=a31+b21=3a+2b
Solving these two equations, we get a=2 and b=−1
Hence, the final solution is −
Fn=2.3n+(−1).2n=2.3n−2n
Note the term ”composed” is used, because if a sequence a0nbalso
satisfies therecurrence of an, then an + a’nsatisfies the recurrence of an as
well, as doesmultiples of an
16
3.3.3 GENERATING FUNCTIONS
The generating function for the sequence a0, a1, . . . , ak, . . . of real
numbers is the infiniteseries
where c1, c2,...,ck are real numbers and F (n) is a function not identically
zero depending only on n. The recurrence relation an = c1an−1 + c2an−2 +···+
ckan−k is called the associated homogeneous recurrence relation. It plays an
important role in the solution of the nonhomogeneous recurrence relation.
Tower of Honoi
The Tower of Hanoi A popular puzzle of the late nineteenth
century invented by the French mathematician Édouard Lucas, called the
Tower of Hanoi, consists of three pegs mounted on a board together with
disks of different sizes. Initially these disks are placed on the first peg in
order of size, with the largest on the bottom (as shown in Figure 2). The
rules of the puzzle allow disks to be moved one at a time from one peg to
another as long as a disk is never placed on top of a smaller disk. The goal
of the puzzle is to have all the disks on the second peg in order of size,
with the largest on the bottom. Let Hn denote the number of moves needed
to solve the Tower of Hanoi problem with n disks. Set up a recurrence
relation for the sequence {Hn}. Solution: Begin with n disks on peg 1. We
can transfer the top n − 1 disks, following the rules of the puzzle, to peg 3
using Hn−1 moves (see Figure 3 for an illustration of the pegs and disks at
this point). We keep the largest disk fixed during these moves. Then, we
17
use one move to transfer the largest disk to the second peg. We can
transfer the n − 1 disks on peg 3 to peg 2 using Hn−1 additional moves,
placing them on top of the largest disk, which always stays fixed on the
bottom of peg 2. Moreover, it is easy to see that the puzzle cannot be
solved using fewer steps. This shows that Hn= 2Hn−1 + 1. The initial
condition is H1 = 1, because one disk can be transferred from peg 1 to peg
2, according to the rules of the puzzle, in one move
3.4 SUMMARY
3.5 EXERCISE
c) How many ways are there to deposit $10 for a bookof stamps?
3.6 REFERENCES
19
4. Elements of Discrete Mathematics: C.L. Liu , Tata McGraw- Hill
Edition .
5. Concrete Mathematics (Foundation for Computer Science): Graham,
Knuth, Patashnik Second Edition, Pearson Education.
6. Discrete Mathematics: Semyour Lipschutz, Marc Lipson, Schaum’s out
lines, McGraw- Hill Inc.
7. Foundations in Discrete Mathematics: K.D. Joshi, New Age
Publication, New Delhi.
20
Unit - II
Counting Principles, Languages and Finite
State Machine
4
PERMUTATIONS AND COMBINATIONS
Unit Structure: -
4.1 Introduction.
4.2 Permutation and combinations.
4.3 Binomial number and combinations
4.3.1 Pascal’s Identity.
4.3.2Vandermonde’s Identity.
4.4 Permutation and combinations with indistinct objects
4.5 Summary
4.6 Exercise
4.7 References
4.1INTRODUCTION
Problem 2: Suppose that there are eight runners in a race. The winner
receives a gold medal, the second place finisher receives a silver medal,
and the third-place finisher receives a bronze medal. How many different
ways are there to award these medals, if all possible outcomes of the race
can occur and there are no ties?
Solution: The number of possible paths between the cities is the number
of permutations of seven elements, because the first city is determined, but
the remaining seven can be ordered arbitrarily. Consequently, there are 7!
= 7 · 6 · 5 · 4 · 3 · 2 · 1 = 5040 ways for the saleswoman to choose her tour.
If, for instance, the saleswoman wishes to find the path between the cities
with minimum distance, and she computes the total distance for each
possible path, she must consider a total of 5040 paths!
22
Combinations
An r-combination of elements of a set is an unordered selection of
r elements from the set. Thus, an r-combination is simply a subset of the
set with r elements.It is denoted by C(n,r) and given by n! /[r! (n-r)!]
Example 2: - How many poker hands of five cards can be dealt from a
standard deck of 52 cards? Also, how many ways are there to select 47
cards from a standard deck of 52 cards?
Solution: Because the order in which the five cards are dealt from a deck
of 52 cards does not matter, there are
C(52, 5) =
different hands of five cards that can be dealt. To compute the value of
C(52, 5), first divide the numerator and denominator by 47! to obtain
C(52, 5) =
C(30, 6) = = = 593,775.
23
Example 4 : How many bit strings of length n contain exactly r 1s?
Binomial Number:-
Binomial number is a number of the form ,where ,
and are integers. Binomial numbers can be factored algebraically as
(1)
for all ,
(2)
for odd, and
(3)
for all positive integers . For example,
(4)
(5)
(6)
(7)
(8)
(9)
(10)
(11)
(12)
and
(13)
(14)
(15)
(16)
(17)
(18)
(19)
(20)
(21)
Proof: Suppose that there are m items in one set and n items in a second
set. Then the total number of ways to pick r elements from the union of
these sets is m + n r . Another way to pick r elements from the union is to
pick k elements from the second set and then r − k elements from the first
set, where k is an integer with 0 ≤ k ≤ r. Because there are n k ways to
choose k elements from the second set and m r − k ways to choose r − k
elements from the first set, the product rule tells us that this can be done in
m r − k n k ways. Hence, the total number of ways to pick r elements
25
from the union also equals r k = 0 m r−k n k . We have found two
expressions for the number of ways to pick r elements from the union of a
set with m items and a set with n items. Equating them gives us
Vandermonde’s identity.
4.5 SUMMARY
4.6 EXERCISE
26
6. How many ways are there for eight men and five women to stand in a
line so that no two women stand next to each other? [Hint: First position
the men and then consider possible positions for the women.]
7. How many ways are there for 10 women and six men to stand in a line
so that no two men stand next to each other? [Hint: First position the
women and then consider possible positions for the men.]
8. One hundred tickets, numbered 1, 2, 3,..., 100, are sold to 100 different
people for a drawing. Four different prizes are awarded, including a grand
prize (a trip to Tahiti). How many ways are there to award the prizes if
a) there are no restrictions?
b) the person holding ticket 47 wins the grand prize?
c) the person holding ticket 47 wins one of the prizes?
d) the person holding ticket 47 does not win a prize?
e) the people holding tickets 19 and 47 both win prizes?
f ) the people holding tickets 19, 47, and 73 all winprizes?
g) the people holding tickets 19, 47, 73, and 97 all winprizes?
h) none of the people holding tickets 19, 47, 73, and 97wins a prize?
i) the grand prize winner is a person holding ticket 19 ,47, 73, or 97?
j) the people holding tickets 19 and 47 win prizes, butthe people
holding tickets 73 and97 do not win prizes?
4.7 REFERENCES
27
5
COUNTING PRINCIPLES, LANGUAGES
AND FINITE STATE MACHINE
Unit Structure: -
5.1 Introduction.
5.2 Basic Counting Principles
5.3 Inclusion Exclusion
5.4 Tree Diagrams
5.5 Summary
5.6 Exercise
5.7 References
5.1INTRODUCTION
There are two basic counting principles Product rule and Sum rule
28
Sanchez, which can be done in 11 ways. By the product rule, there are 12 ·
11 = 132 ways to assign offices to these two employees.
THE SUM RULE If a task can be done either in one of n1 ways or in one
of n2 ways, where none of the set of n1 ways is the same as any of the set
of n2 ways, then there are n1 + n2 ways to do the task.
29
5.4 TREE DIAGRAMS
Figure 1
EXAMPLE 4 How many bit strings of length four do not have two
consecutive 1s?
Solution: The tree diagram in Figure 1 displays all bit strings of length
four without two consecutive 1s. We see that there are eight bit strings of
length four without two consecutive 1s.
The pigeonhole principle is also called the Dirichlet drawer principle, after
the nineteenth century German mathematician G. Lejeune Dirichlet, who
often used this principle in his work.
(Dirichlet was not the first person to use this principle; a demonstration
that there were at least two Parisians with the same number of hairs on
their heads dates back to the 17th century) It is an important additional
proof technique supplementing those we have developed in earlier
chapters. We introduce it in this chapter because of its many important
applications to combinatorics.
EXAMPLE 1 Among any group of 367 people, there must be at least two
with the same birthday, because there are only 366 possible birthdays.
5.5 SUMMARY
5.6 EXERCISE
31
a) In how many ways can two representatives be picked so that one is a
mathematics major and the other is a computer science major?
b) In how many ways can one representative be picked who is either a
mathematics major or a computer science major?
2. An office building contains 27 floors and has 37 officeson each floor.
How many offices are in the building?
3. A multiple-choice test contains 10 questions. There arefour possible
answers for each question.
a) In how many ways can a student answer the questionson the test if the
student answers every question?
b) In how many ways can a student answer the questionson the test if the
student can leave answers blank?
4. A particular brand of shirt comes in 12 colors, has a male version and a
female version, and comes in three sizes for each sex. How many
different types of this shirt a remade?
5. Six different airlines fly from New York to Denver andseven fly from
Denver to San Francisco. How many different pairs of airlines can you
choose on which to booka trip from New York to San Francisco via
Denver, when you pick an airline for the flight to Denver and an
airline for the continuation flight to San Francisco?
6. There are four major auto routes from Boston to Detroit and six from
Detroit to Los Angeles. How many major auto routes are there from
Boston to Los Angeles via Detroit?
7. How many different three-letter initials can people have?
8. How many different three-letter initials with none of the letters repeated
can people have?
9. How many different three-letter initials are there that begin with an A?
10. How many bit strings are there of length eight?
11. How many bit strings of length ten both begin and end with a 1?
12. How many bit strings are there of length six or less, not counting the
empty string?
13. How many bit strings with length not exceeding n, wheren is a positive
integer, consist entirely of 1s, not counting the empty string?
14. How many bit strings of length n, where n is a positive integer, start
and end with 1s?
15. How many strings are there of lowercase letters of length four or less,
not counting the empty string?
16. How many strings are there of four lowercase letters thathave the letter
x in them?
32
5.7 REFERENCES
33
6
COUNTING PRINCIPLES, LANGUAGES
AND FINITE STATE MACHINE
Unit Structure: -
6.1 Introduction.
6.2 Languages and Grammars.
6.3 Phrase-Structure Grammars.
6.4 Types of Phrase-Structure Grammars
6.5 Finite-State Machines with Output
6.6 Finite-State Automata
6.7 Regular Sets and Regular Grammars
6.8 Turing machine
6.9 Godel Numbers
6.10 Summary
6.11 Exercise
6.12 References
6.1 INTRODUCTION
34
language, is specified by a well-defined set of rules of syntax. Rules of
syntax are important not only in linguistics, the study of natural languages,
but also in the study of programming languages.
35
precisely, a grammar has a vocabulary V , which is a set of symbols used
to derive members of the language.
Some of the elements of the vocabulary cannot be replaced by
other symbols. These are called terminals, and the other members of the
vocabulary, which can be replaced by other symbols, are called
nonterminals. The sets of terminals and nonterminals are usually denoted
by T and N, respectively. In the example given in the introduction of the
section, the set of terminals is {a, the, rabbit, mathematician, hops, eats,
quickly, wildly}, and the set of nonterminals is {sentence, noun phrase,
verb phrase, adjective, article, noun, verb, adverb}. There is a special
member of the vocabulary called the start symbol, denoted by S, which is
the element of the vocabulary that we always begin with. In the example
in the introduction, the start symbol is sentence. The rules that specify
when we can replace a string from V ∗, the set of all strings of elements in
the vocabulary, with another string are called the productions of the
grammar. We denote by z0 → z1 the production that specifies that z0 can
be replaced by z1 within a string. The productions in the grammar given in
the introduction of this section were listed. The first production, written
using this notation, is sentence → noun phrase verb phrase. We
summarize this terminology in Definition 2.
36
Type 2 grammars are called context-free grammars because a
nonterminal symbol that is the left side of a production can be replaced in
a string whenever it occurs, no matter what else is in the string.A language
generated by a type 2 grammar is called a context-free language. When
there is a production of the form lw1r → lw2r (but not of the form w1 →
w2), the grammar is called type 1 or context-sensitive because w1 can be
replaced by w2 only when it is surrounded by the strings l and r. A
language generated by a type 1 grammar is called a context-sensitive
language. Type 3 grammars are also called regular grammars. A language
generated by a regular grammar is called regular. Section 13.4 deals with
the relationship between regular languages and finite-state machines.
37
An input string takes the starting state through a sequence of states,
as determined by the transition function. As we read the input string
symbol by symbol (from left to right), each input symbol takes the
machine from one state to another. Because each transition produces an
output, an input string also produces an output string.
Suppose that the input string is x = x1x2 . . . xk. Then, reading this
input takes the machine from state s0 to state s1, where s1 = f (s0, x1), then
to state s2, where s2 = f (s1, x2), and so on, with sj = f (sj−1, xj ) for j = 1, 2,
. . . , k, ending at state sk = f (sk−1, xk). This sequence of transitions
produces an output string y1y2 . . . yk, where y1 = g(s0, x1) is the output
corresponding to the transition from s0 to s1, y2 = g(s1, x2) is the output
corresponding to the transition from s1 to s2, and so on. In general, yj =
g(sj−1, xj ) for j = 1, 2, . . . , k. Hence, we can extend the definition of the
output function g to input strings so that g(x) = y, where y is the output
corresponding to the input string x. This notation is useful in many
applications.
38
6.6 FINITE-STATE AUTOMATA
39
A∗represents the Kleene closure of the set represented by A.
Sets represented by regular expressions are called regular sets. Henceforth
regular expressions will be used to describe regular sets, so when we refer
to the regular set A, we will mean the regular set represented by the
regular expression A. Note that we will leave out outer parentheses from
regular expressions when they are not needed.
EXAMPLE 1 What are the strings in the regular sets specified by the
regular expressions 10∗, (10)∗, 0 ∪01,
0(0 ∪1)∗, and (0∗1)∗?
Solution: (a) To construct a regular expression for the set of bit strings
with even length, we use the fact that such a string can be obtained by
concatenating zero or more strings each consisting of two bits. The set of
strings of two bits is specified by the regular expression (00 ∪01 ∪10
∪11). Consequently, the set of strings with even length is specified by (00
∪01 ∪10 ∪11)* .
(b) A bit string ending with a 0 and not containing 11 must be the
concatenation of one or more strings where each string is either a 0 or a
10. (To see this, note that such a bit string must consist of 0 bits or 1 bits
each followed by a 0; the string cannot end with a single 1 because we
know it ends with a 0.) It follows that the regular expression (0 ∪10)∗ (0
∪10) specifies the set of bit strings that do not contain 11 and end with a
0. [Note that the set specified by (0 ∪10)∗includes the empty string,
which is not in this set, because the empty string does not end with a 0.]
(c) A bit string containing an odd number of 0s must contain at least one 0,
which tells us that it starts with zero or more 1s, followed by a 0, followed
by zero or more 1s. That is, each such bit string begins with a string of the
form 1j 01k for nonnegative integersj and k. Because the bit string
40
contains an odd number of 0s, additional bits after this initial block can be
split into blocks each starting with a 0 and containing one more 0. Each
such block is of the form 01p01q, where p and q are nonnegative integers.
Consequently, the regular expression 1∗01∗(01∗01∗)∗specifies the set of
bit strings with an odd number of 0s.
41
6.8 TURING MACHINE
At each step, the control unit reads the current tape symbol x. If the control
unit is in state s and if the partial function f is defined for the pair (s, x)
with f (s, x) = (s, x, d), the control unit
1. enters the state s’,
2. writes the symbol x in the current cell, erasing x, and
3. moves right one cell if d = R or moves left one cell if d = L.
We write this step as the five-tuple (s, x, s’, x’, d). If the partial function f
is undefined for the pair (s, x), then the Turing machine T will halt.
A common way to define a Turing machine is to specify a set of five-
tuples of the form (s, x, s’, x’, d). The set of states and input alphabet is
implicitly defined when such a definition is used.
EXAMPLE 1 What is the final tape when the Turing machine T defined
by the seven fivetuples(s0, 0, s0, 0, R), (s0, 1, s1, 1, R), (s0, B, s3, B, R),
(s1, 0, s0, 0, R), (s1, 1, s2, 0, L)
(s1, B, s3, B, R), and (s2, 1, s3, 0, R) is run on the tape shown in Figure
2(a)?
43
Solution: We start the operation with T in state s0 and with T positioned
over the leftmost nonblank symbol on the tape. The first step, using the
five-tuple (s0, 0, s0, 0, R), reads the 0 in the leftmost nonblank cell, stays
in state s0, writes a 0 in this cell, and moves one cell right.
The second step, using the five-tuple (s0, 1, s1, 1, R), reads the 1 in the
current cell, enters state s1, writes a 1 in this cell, and moves one cell
right. The third step, using the five-tuple (s1, 0, s0, 0, R), reads the 0 in the
current cell, enters state s0, writes a 0 in this cell, and moves one cell
right. The fourth step, using the five-tuple (s0, 1, s1, 1, R), reads the 1 in
the current cell, enters state s1, writes a 1 in this cell, and moves right one
cell. The fifth step, using the five-tuple (s1, 1, s2, 0, L), reads the 1 in the
current cell, enters state s2, writes a 0 in this cell, and moves left one cell.
44
The sixth step, using the five-tuple (s2, 1, s3, 0, R), reads the 1 in the
current cell, enters the state s3, writes a 0 in this cell, and moves right one
cell. Finally, in the seventh step, the machine halts because there is no
five-tuple beginning with the pair (s3, 0) in the description of the machine.
6.10 SUMMARY
45
6.11 EXERCISE
6.12 REFERENCES
7
GRAPHS
Unit Structure
7.0 Objective
7.1 Definition
7.2 Adjacency matrix
7.3 path matrix
7.4 Representing relations using diagraphs
7.5 Warshall’s algorithm- shortest path
7.6 Linked representation of a graph
7.7 Operations on graph with algorithms
7.8 Traversing a graph-
7.8.1 Breadth-First search and
7.8.2 Depth-First search.
7.0 OBJECTIVE
● This chapter will cover these topics like Graphs, directed graphs ,
operations on graphs , finding shortest paths which appear in many
areas of mathematics and computer science.
● Graphs are discrete structures consisting of vertices and edges that
connect these vertices. There are different kinds of graphs, depending
on whether edges have directions, whether multiple edges can connect
the same pair of vertices, and whether loops are allowed.
● We will describe how graphs can be used to model acquaintanceships
between people, collaboration between researchers, telephone calls
between telephone numbers, and links between websites.
● We will show how graphs can be used to model roadmaps and the
assignment of jobs to employees of an organization.
● Graphs can be used to determine whether a circuit can be implemented
on a planar circuit board.
● We can determine whether two computers are connected by a
communications link using graph models of computer networks.
● Graphs with weights assigned to their edges can be used to solve
problems such as finding the shortest path between two cities in a
transportation network.
47
● We can also use graphs to schedule exams and assign channels to
television stations.
● This chapter will introduce the basic concepts of graph theory and
present many different graph models.
● To solve the wide variety of problems that can be studied using
graphs, we will introduce many different graph algorithms. We will
also study the complexity of these algorithms.
Figure 1
48
(i) V consists of vertices A, B, C, D.
(ii) E consists of edges as follows:
e1 = {A,B}, e2 = {B,C}, e3 = {C,D}, e4 = {A,C}, e5 = {B,D}.
Figure 2
50
Isomorphic Two graphs are said to be isomorphic if there is
Graph one to one correspondence between their vertices
and their edges such that incidences are preserved
Properties preserved by isomorphism of graphs.
• must have the same number of vertices
• must have the same number of edges
• must have the same number of vertices with
degree k
• for every proper subgraph g of one graph, there
must be a proper subgraph of the other graph that
is isomorphic of g
Figure 3
51
An Adjacency List for a Simple Graph.
a b, c, e
b A
c a, d, e
d c, e
e a, c, d
Figure 4
An Adjacency List for a Directed Graph.
Initial Vertex Terminal Vertices
a b, c, d, e
b b, d
c a, c, e
d -
e b, c, d
To simplify computation, graphs can be represented using
matrices.
52
Definition:
Suppose that G = (V , E) is a simple graph with n vertices i.e |V | = n.
Suppose that the vertices of G are listed arbitrarily as v1, v2,..., vn. The
adjacency matrix A (or AG) of G, with respect to this listing of the
vertices, is the n x n zero–one matrix with 1 as its (i, j )th entry when vi
and vj are adjacent, and 0 as its (i, j )th entry when they are not adjacent.
Figure 5
Solution:
Things to remember:
● The adjacency matrix of a simple graph is symmetric, that is,aij =
aji, because both of these entries are 1 when vi and vj are adjacent, and
both are 0 otherwise. Furthermore, because a simple graph has no
loops, each entry aii, i = 1, 2, 3,...,n, is 0.
53
● Example: Adjacency matrix for given graph is :
Figure 6
Definition:
Let G be a graph with m edges, and u and v be any two vertices in G. The
path matrix for vertices u and v denoted by P(u, v) = [pi j]q×m , where q is
the number of different paths between u and v.
54
In other word,
Clearly, a path matrix is defined for a particular pair of vertices, the rows
in P(u, v) correspond to different paths between u and v, and the columns
correspond to different edges in G.
Figure 7
Ordered Pairs –
● In this set of ordered pairs of x and y are used to represent relation.
In this corresponding values of x and y are represented using
parenthesis.
● Example: {(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)}
56
● Example:
Let P = {1, 2, 3, 4}, Q = {a, b, c, d}
and R = {(1, a), (1, b), (1, c), (2, b), (2, c), (2, d)}.
The matrix of relation R is shown as fig:
Digraph –
● A digraph is known was directed graph. It consists of set ‘V’ of
vertices and with the edges ‘E’.
● Here E is represented by ordered pair of Vertices.
● In the edge (a, b), a is the initial vertex and b is the final vertex.
● If edge is (a, a) then this is regarded as loop.
● Example: Suppose we have relation forming
R = {(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)}
This relation is represented using digraph as:
Figure 8
● The Floyd Warshall Algorithm is for solving the All Pairs Shortest
Path problem.
● The problem is to find shortest distances between every pair of
vertices in a given edge weighted directed Graph.
57
● We initialize the solution matrix same as the input graph matrix as a
first step.
● Then we update the solution matrix by considering all vertices as an
intermediate vertex.
● The idea is to one by one pick all vertices and updates all shortest
paths which include the picked vertex as an intermediate vertex in the
shortest path.
● When we pick vertex number k as an intermediate vertex, we already
have considered vertices {0, 1, 2, .. k-1} as intermediate vertices.
● For every pair (i, j) of the source and destination vertices respectively,
there are two possible cases.
1) k is not an intermediate vertex in shortest path from i to j.
We keep the value of dist[i][j] as it is.
2) k is an intermediate vertex in shortest path from i to j.
We update the value of
dist[i][j] as dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] + dist[k][j]
58
Example:
Let the given graph be:
Figure 9
Solution:
Follow the steps below to find the shortest path between all the
pairs of vertices.
The row and the column are indexed as i and j respectively. i and j
are the vertices of the graph.
Each cell A[i][j] is filled with the distance from the ith vertex to the jth
vertex.
If there is no path from ith vertex to jth vertex, the cell is left as infinity.
2. Now, create a matrix A1 using matrix A0. The elements in the first
column and the first row are left as they are. The remaining cells are
filled in the following way.
That is, if the direct distance from the source to the destination is
greater than the path through the vertex k, then the cell is filled with
A[i][k] + A[k][j].
In this step, k is the second vertex (i.e. vertex 2). The remaining
steps are the same as in step 2.
60
7.6 LINKED REPRESENTATION OF A GRAPH:
If all the adjacent nodes are traversed then store the NULL in the
pointer field of last node of the list.
61
7.7 OPERATIONS ON GRAPH WITH ALGORITHMS -
The idea is to represent the graph as a list of linked lists where the
head of the linked list is the vertex and all the connected linked lists are
the vertices to which it is connected.
For example,
if 5 needs to be added between vertex 2 and vertex 3 such that vertex 3
points to vertex 5 and vertex 5 points to vertex 2,
then a new edge is created between vertex 5 and vertex 3 and a new edge
is created from vertex 5 and vertex 2.
After adding the vertex, the adjacency list changes to:
62
If the edge is present, then delete the vertex in the same way as
delete is performed in a linked list.
For example, the adjacency list translates to the below list if vertex
4 is deleted from the list:
Our test graph G with its adjacency structure appears in given Fig.
where we assume the vertices are ordered alphabetically.
Figure 10
63
During the execution of our algorithms, each vertex (node) N of G
will be in one of three states, called the status of N, as follows:
STATUS = 1: (Ready state) The initial state of the vertex N.
STATUS = 2: (Waiting state) The vertex N is on a (waiting) list,
waiting to be processed.
STATUS = 3: (Processed state) The vertex N has been processed.
Depth-first Search:
64
Algorithm
Step 1: SET STATUS = 1 (ready state) for each node in G
Step 2: Push the starting node A on the stack and set its STATUS = 2
(waiting state)
Step 3: Repeat Steps 4 and 5 until STACK is empty
Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed
state)
Step 5: Push on the stack all the neighbours of N that are in the ready state
(whose STATUS = 1) and set their
STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT
Example :
Consider the graph G along with its adjacency list, given in the
figure below. Calculate the order to print all the nodes of the graph starting
from node H, by using depth first search (DFS) algorithm.
Figure 11
Solution :
Push H onto the stack
STACK : H
POP the top element of the stack i.e. H, print it and push all the neighbours
of H onto the stack that are is ready state.
Print H
STACK : A
Pop the top element of the stack i.e. A, print it and push all the neighbours
of A onto the stack that are in ready state.
Print A
Stack : B, D
Pop the top element of the stack i.e. D, print it and push all the neighbours
of D onto the stack that are in ready state.
65
Print D
Stack : B, F
Pop the top element of the stack i.e. F, print it and push all the neighbours
of F onto the stack that are in ready state.
Print F
Stack : B
Pop the top of the stack i.e. B and push all the neighbours
Print B
Stack : C
Pop the top of the stack i.e. C and push all the neighbours.
Print C
Stack : E, G
Pop the top of the stack i.e. G and push all its neighbours.
Print G
Stack : E
Pop the top of the stack i.e. E and push all its neighbours.
Print E
Stack :
Hence, the stack now becomes empty and all the nodes of the graph have
been traversed.
H→A→D→F→B→C→G→E
Breadth-First search:
● The general idea behind a breadth-first search beginning at a starting
vertex A is as follows. First we process the starting vertex A.
● Then we process all the neighbors of A.
● Then we process all the neighbors of neighbors of A. And so on.
● Naturally we need to keep track of the neighbors of a vertex, and we
need to guarantee that
● no vertex is processed twice.
● This is accomplished by using a QUEUE to hold vertices that are
waiting to be processed, and by a field STATUS which tells us the
current status of a vertex.
● The breadth-first search (BFS) algorithm appears in Fig. 8-33, Again
the algorithm will process only those vertices which are connected to
the starting vertex A, that is, the connected component including A.
66
● Suppose one wants to process all the vertices in the graph G. Then the
algorithm must be modified so that it begins again with another vertex
(which we call B) that is still in the ready state (STATUS = 1).
● This vertex B can be obtained by traversing through the list of vertices.
● Breadth first search is a graph traversal algorithm that starts traversing
the graph from root node and explores all the neighbouring nodes.
● Then, it selects the nearest node and explore all the unexplored nodes.
● The algorithm follows the same process for each of the nearest node
until it finds the goal.
● The algorithm of breadth first search is given below.
● The algorithm starts with examining the node A and all of its
neighbours.
● In the next step, the neighbours of the nearest node of A are explored
and process continues in the further steps.
● The algorithm explores all neighbours of all the nodes and ensures that
each node is visited exactly once and no node is visited twice.
Algorithm
Step 1: SET STATUS = 1 (ready state)
for each node in G
Step 6: EXIT
Example
Consider the graph G shown in the following image, calculate the
minimum path p from node A to node E. Given that each edge has a length
of 1.
67
Solution:
Minimum Path P can be found by applying breadth first search
algorithm that will begin at node A and will end at E. the algorithm uses
two queues, namely QUEUE1 and QUEUE2. QUEUE1 holds all the
nodes that are to be processed while QUEUE2 holds all the nodes that are
processed and deleted from QUEUE1.
Lets start examining the graph from Node A.
1. Add A to QUEUE1 and NULL to QUEUE2.
QUEUE1 = {A}
QUEUE2 = {NULL}
2. Delete the Node A from QUEUE1 and insert all its neighbours. Insert
Node A into QUEUE2
QUEUE1 = {B, D}
QUEUE2 = {A}
3. Delete the node B from QUEUE1 and insert all its neighbours. Insert
node B into QUEUE2.
QUEUE1 = {D, C, F}
QUEUE2 = {A, B}
4. Delete the node D from QUEUE1 and insert all its neighbours. Since F
is the only neighbour of it which has been inserted, we will not insert it
again. Insert node D into QUEUE2.
QUEUE1 = {C, F}
QUEUE2 = { A, B, D}
5. Delete the node C from QUEUE1 and insert all its neighbours. Add
node C to QUEUE2.
QUEUE1 = {F, E, G}
QUEUE2 = {A, B, D, C}
6. Remove F from QUEUE1 and add all its neighbours. Since all of its
neighbours has already been added, we will not add them again. Add node
F to QUEUE2.
QUEUE1 = {E, G}
QUEUE2 = {A, B, D, C, F}
68
7. Remove E from QUEUE1, all of E's neighbours has already been added
to QUEUE1 therefore we will not add them again. All the nodes are
visited and the target node i.e. E is encountered into QUEUE2.
QUEUE1 = {G}
QUEUE2 = {A, B, D, C, F, E}
Now, backtrack from E to A, using the nodes available in QUEUE2.
7.9 EXERCISE
69
8
TREES
Unit Structure
8.0 Objective
8.1 Definition
8.2 Ordered rooted tree
8.3 Binary trees
8.4 Complete and extended binary trees
8.5 Representing binary trees in memory
8.6 Traversing binary trees
8.7 Binary search tree
8.7.1 Algorithms for searching and inserting in binary search trees
8.7.2 Algorithms for deleting in a binary search tree
8.8 Exercise
8.0 OBJECTIVE
70
8.1 DEFINITION
Definition of a Tree.
A tree is a connected graph containing no cycles.
Tree –terminologies
Node - an object containing a data value and links to other nodes
Edge - directed link, representing relationships between nodes
Root - The start of the tree. The top-most node in the tree Node without
parents is root node. In figure 1 blue node is tree.
Figure 1
Parent (ancestor) - any node with at least one child. The blue nodes in
given figure 2
Figure 2
71
Child (descendant) - any node with a parent , The blue nodes in given
figure 3
Figure 3
Siblings - all nodes on the same level,The blue nodes in given figure 4
Figure 4
Internal node - a node with at least one children (except root) All the
orange nodes as shown in figure 5
Figure 5
External node - a node without children All the orange nodes as shown in
figure 6
Figure 6
72
General Trees
A tree or general trees is defined as a non-empty finite set of elements
called vertices or nodes having the property that each node can have
minimum degree 1 and maximum degree n.
It can be partitioned into n+1 disjoint subsets such that the first subset
contains the root of the tree and remaining n subsets includes the elements
of the n subtree.
Example:
Figure 7
Ordered Trees:
If in a tree at each level, an ordering is defined, then such a tree is
called an ordered tree.
Example:
Figure 8
Properties of Trees
In this section we will discuss about properties of trees; what makes
them special and how they can be used.
73
● A tree T with n vertices has n-1 edges.
● A graph is a tree if and only if it a minimal connected.
Definition:
If a directed tree has exactly one node or vertex called root whose
incoming degree is 0 and all other vertices have incoming degree one,
then the tree is called a rooted tree.
Figure 9
● Data is often structured like a tree.
● For example, a book has a tree structure: draw a vertex for the
book itself.
Then draw vertices for each chapter, connected to the book vertex.
Under each chapter, draw a vertex for each section, connecting it
to the chapter it belongs to.
74
The graph will not have any cycles; it will be a tree.
But a tree with clear hierarchy which is not present if we don't
identify the book vertex as the “top”.
● As soon as one vertex of a tree is designated as the root, then every
other vertex on the tree can be characterized by its position relative
to the root.
● This works because there is a unique path between any two
vertices in a tree.
● So from any vertex, we can travel back to the root in exactly one
way.
● This also allows us to describe how distinct vertices in a rooted
tree are related.
● If two vertices are adjacent, then we say one of them is the parent
of the other, which is called the child of the parent.
● Of the two, the parent is the vertex that is closer to the root.
● Thus the root of a tree is a parent, but is not the child of any vertex
(and is unique in this respect: all non-root vertices have exactly
one parent).
● The child of a child of a vertex is called the grandchild of the
vertex (and it is the grandparent).
● More in general, we say that a vertex v is a descendent of a vertex
u provided u is a vertex on the path from v to the root.
● Then we would call u an ancestor of v.
● For most trees (in fact, all except paths with one end the root),
there will be pairs of vertices neither of which is a descendant of
the other.
● We might call these cousins or siblings.
● In fact, vertices u and v are called siblings provided they have the
same parent.
● In a rooted tree, the depth or level of a vertex v is its distance from
the root, i.e., the length of the unique path from the root to v. Thus,
the root has depth 0.
● The height of a rooted tree is the length of a longest path from the
root (or the greatest depth in the tree).
● A leaf in a rooted tree is any vertex having no children.
75
Example :
Figure 10
We can say,
1. The height of this tree is 3. Also,
2. r, a, b, c, and d are the internal vertices;
3. vertices e, f, g, h, i, and j are the leaves;
4. vertices g, h, and i are siblings;
5. vertex a is an ancestor of j; and
6. j is a descendant of a.
A tree consisting of the nodes (empty tree) is also a binary tree. A binary
tree is shown in figure 11
Basic Terminology:
● Root: A binary tree has a unique node called the root of the tree.
● Left Child: The node to the left of the root is called its left child.
● Right Child: The node to the right of the root is called its right
child.
Definition:
A binary tree is an ordered 2-ary tree in which each child is designated
either a left-child or a right-child.
76
Example:
Figure 11
A complete binary tree is a binary tree in which all the levels are
completely filled except possibly the lowest one, which is filled from the
left.
A complete binary tree is just like a full binary tree, but with two
major differences. All the leaf elements must lean towards the left.
Figure 12
● A complete binary tree is just like a full binary tree, but with two
major differences:
○ All the leaf elements must lean towards the left.
○ The last leaf element might not have a right sibling i.e. a complete
binary tree doesn't have to be a full binary tree.
Creation of Complete Binary Tree:
77
Suppose we have an array of 6 elements shown as below:
Step 1: First, we will select the first element of the array, i.e., 1, and make
a root node of the tree. The number of elements available in the first level
is 1.
Step 2: Now, we will select the second and third elements of the array.
Keep the second element and third element of the array as the left and
right child of the root node respectively shown as below:
As we can observe above that nodes 4 and 5 are the left and right child of
node 2 respectively.
Step 4: Now, we will select the last element of the array, i.e., 6, and keep it
as left child of the node 3 as we know that in a complete binary tree, the
nodes are filled from the left side shown as below:
78
As we can observe that the second level contains 3 elements.
1. Linked representation
➢ Binary trees in linked representation are stored in the memory as
linked lists.
➢ These lists have nodes that aren’t stored at adjacent or neighboring
memory locations and are linked to each other through the parent-
child relationship associated with trees.
➢ In this representation, each node has three different parts –
○ pointer that points towards the right node,
○ pointer that points towards the left node,
○ data element.
➢ This is the more common representation.
79
➢ All binary trees consist of a root pointer that points in the direction
of the root node.
➢ When you see a root node pointing towards null or 0, you should
know that you are dealing with an empty binary tree.
➢ The right and left pointers store the address of the right and left
children of the tree.
2. Sequential representation
➢ Although it is simpler than linked representation, its inefficiency
makes it a less preferred binary tree representation of the two.
➢ The inefficiency lies in the amount of space it requires for the
storage of different tree elements.
➢ The sequential representation uses an array for the storage of tree
elements.
➢ The number of nodes a binary tree has defines the size of the array
being used.
➢ The root node of the binary tree lies at the array’s first index.
➢ The index at which a particular node is stored will define the
indices at which the right and left children of the node will be
stored.
➢ An empty tree has null or 0 as its first index.
1. Preorder Traversal:
● The preorder traversal of a binary tree is a recursive process.
● The preorder traversal of a tree is:
○ Visit the root of the tree.
○ Traverse the left subtree in preorder.
○ Traverse the right subtree in preorder.
2. Postorder Traversal:
● The postorder traversal of a binary tree is a recursive process.
● The postorder traversal of a tree is
○ Traverse the left subtree in postorder.
○ Traverse the right subtree in postorder.
○ Visit the root of the tree.
3. Inorder Traversal:
● The inorder traversal of a binary tree is a recursive process.
● The inorder traversal of a tree is
○ Traverse in inorder the left subtree.
○ Visit the root of the tree.
○ Traverse in inorder the right subtree.
81
Example: Determine the preorder, postorder and inorder traversal of the
binary tree as shown in figure 13
Figure 13
Binary search trees have the property that the node to the left contains
a smaller value than the node pointing to it and the node to the right
contains a larger value than the node pointing to it.
● It is not necessary that a node in a 'Binary Search Tree' point to the
nodes whose value immediately precede and follow it.
Figure 14
Algorithm for : Inserting into a Binary Search Tree:
Consider a binary tree T.
Suppose we have given an ITEM of information to insert in T.
The ITEM is inserted as a leaf in the tree.
82
The following steps explain a procedure to insert an ITEM in the binary
search tree T.
I. Compare the ITEM with the root node.
II. If ITEM>ROOT NODE, proceed to the right child, and it becomes
a root node for the right subtree.
III. If ITEM<ROOT NODE, proceed to the left child.
IV. Repeat the above steps until we meet a node which has no left and
right subtree.
V. Now if the ITEM is greater than the node, then the ITEM is
inserted as the right child, and if the ITEM is less than the node,
then the ITEM is inserted as the left child.
Example: Show the binary search tree after inserting 3, 1,4,6,9,2,5,7 into
an initially empty binary search tree.
Solution: The insertion of the above nodes in the empty binary search tree
is shown in figure 15:
Figure 15
Solution:
To delete the root node, first replace the root node with the closest
elements of the root.
For this, first, move one step left and then to the right as far as possible to
the node.
Then delete the replaced node. The tree after deletion shown in figure 16
Figure 16
84
8.8 EXERCISE:
85