DS_notes
Transcript of DS_notes
-
7/26/2019 DS_notes
1/105
-
7/26/2019 DS_notes
2/105
PDM MCA 2
What is Data Structure
In computer science, a data structure is a particular
way of storing and organizing data in a computer so
that it can e used efficiently!
Data may e organized in many different ways, the
logical or mathematical model of aparticular
organization of data in memory or ondis" is called
Data Structure!Algorithms are used for manipulationof data!
05/20/16
-
7/26/2019 DS_notes
3/105
Data Structure #perations
$he data appearing in our data structure is processed y means of certainoperations! $he following four operations play a ma%or role&
$rans'ersing
Accessing each record e(actly once so that certain items in the record may
eprocessed!)$his accessing or processing is sometimes called *'isiting+ the
records! Searching
-inding the location of the record with a gi'en "ey 'alue, or finding the
locations of all records, which satisfy one or more conditions!
Inserting.
Adding new records to the structure!
Deleting
/emo'ing a record from the structure!
05/20/16 PDM MCA 3
-
7/26/2019 DS_notes
4/105
$ypes of Data structure
$here are two types of data structure
0! 1inear Data Structure
A data structure is said to e linear if its elements form a se2uence, or in other
words a linear list!
I! Array
II! Stac"
III! 3ueue
I4! 1in"ed 1ist
5! 6on7 1inear Data Structure
A non7linear structure is mainly used to represent data containing a hierarchicalrelationship etween elements!
I! $ree
II! 8raph
05/20/16 PDM MCA 4
-
7/26/2019 DS_notes
5/105
A18#/I$9M
Algorithm is a step7y7step procedure for calculations or -inite step
y step to sol'e the finite prolem with finite amount of time! Some
other definition of algorithm are
An algorithm is a set of rules for carrying out calculation either y
hand or on a machine!
An algorithm is a finite step7y7step procedure to achie'e a re2uired
result!
An algorithm is a se2uence of computational steps that transform
the input into the output! An algorithm is a se2uence of operations performed on data that
ha'e to e organized in data structures!
PDM MCA 5
-
7/26/2019 DS_notes
6/105
Algorithm Analysis
$he comple(ity of an algorithm is a functiong)n that gi'es the
upper ound of the numer of operation )or running time
performed y an algorithm when the input size is n!
$here are two interpretations of upper ound!
Worst7case Comple(ity
$he running time for any gi'en size input will e lower than the
upper ound e(cept possily for some 'alues of the input where
the ma(imum is reached!
A'erage7case Comple(ity$he running time for any gi'en size input will e the a'erage
numer of operations o'er all prolem instances for a gi'en size!
PDM MCA 6
-
7/26/2019 DS_notes
7/105
Algorithm Analysis
:ecause, it is 2uite difficult to estimate the statistical eha'ior
of the input, most of the time we content oursel'es to a worst
case eha'ior! Most of the time, the comple(ity of g)n is
appro(imated y its family o)f)n where f)n is one of the
following functions! n )linear comple(ity, log n )logarithmic
comple(ity, na where a ; 5 )polynomial comple(ity, an
)e(ponential comple(ity!
#ptimality
#nce the comple(ity of an algorithm has een estimated, the
2uestion arises whether this algorithm is optimal! An algorithm
PDM MCA 7
-
7/26/2019 DS_notes
8/105
Algorithm Analysis
for a gi'en prolem is optimal if its comple(ity reaches the
lower ound o'er all the algorithms sol'ing this prolem! -or
e(ample, any algorithm sol'ing )n5 comple(ity! If one finds an
#)n5 algorithm that sol'e this prolem, it will e optimal and of
comple(ity ?)n5!
/eductionAnother techni2ue for estimating the comple(ity of a prolem is
the transformation of prolems, also called prolem reduction!
As an e(ample, suppose we "now a lower ound for
PDM MCA 8
-
7/26/2019 DS_notes
9/105
Algorithm Analysis
PDM MCA 9
a prolem A, and that we would li"e to estimate a lower ound
for a prolem :! If we can transform A into : y a
transformation step whose cost is less than that for sol'ing A,
then : has the same ound as A!
-
7/26/2019 DS_notes
10/105
Comple(ity
measurement
space comple(ity is also important& $his is essentially the
numer of memory cells which an algorithm needs
$ime comple(ity of an algorithm 2uantifies the amount of time
ta"en y an algorithm to run
PDM MCA 10
-
7/26/2019 DS_notes
11/105
:ig # 6otation
# notation appro(imates the cost function of an algorithm
@ $he appro(imation is usually good enough, especially whenconsidering the efficiency of algorithm as ngets 'ery large
@ Allows us to estimate rate of function growth
Instead of computing the entire cost function we only need to countthe numer of times that an algorithm e(ecutes its barometerinstruction(s)
@ $he instruction that is e(ecuted the most numer of times in analgorithm )the highest order term
11/320PDM I$
-
7/26/2019 DS_notes
12/105
:ig # 6otation
$he cost function of an algorithm A, tA(n), can e appro(imated yanother, simpler, functiong(n)which is also a function with only 0'ariale, the data size n.
$he functiong(n)is selected such that it represents an upper bound
on the efficiency of the algorithm A )i!e! an upper ound on the'alue of tA(n)!
$his is e(pressed using the ig7# notation& #(g(n))!
-or e(ample, if we consider the time efficiency of algorithm A then
-
7/26/2019 DS_notes
13/105
$op down approach
A top-down approach is essentially the rea"ing down of a
system to gain insight into its compositional su7systems! In a
top7down approach an o'er'iew of the system is formulated,
specifying ut not detailing any first7le'el susystems! ach
susystem is then refined in yet greater detail, sometimes inmany additional susystem le'els, until the entire specification is
reduced to ase elements! A top7down model is often specified
with the assistance of +lac" o(es+, these ma"e it easier to
manipulate! 9owe'er, lac" o(es may fail to elucidate
elementary mechanisms or e detailed enough to realistically
'alidate the model! $op down approach starts with the ig
picture! It rea"s down from there into smaller segments!
PDM MCA 13
-
7/26/2019 DS_notes
14/105
:ottom up approach
A bottom-up approach is the piecing together of systems to
gi'e rise to grander systems, thus ma"ing the original systems
su7systems of the emergent system! :ottom7up processing is
a type of information processing ased on incoming data from
the en'ironment to form a perception! Information enters theeyes in one direction )input, and is then turned into an image
y the rain that can e interpreted and recognized as a
perception )output! In a ottom7up approach the indi'idual
ase elements of the system are first specified in great detail
PDM MCA 14
-
7/26/2019 DS_notes
15/105
String processing
String & A finite se2uence S of zero or more
characters is called string!
String with zero characters is called empty
string!
String will e denoted y enclosing their
characters in single 2uotation mar"s!
!g! B$# :
05/20/16 PDM MCA 15
-
7/26/2019 DS_notes
16/105
Storing Strings
Strings are stored in types of structures
0! -i(ed 1ength Structure
5! 4ariale 1ength Structure with fi(edma(imum
0! 1in"ed Structures!
05/20/16 PDM MCA 16
-
7/26/2019 DS_notes
17/105
String #perations
1. Substring &Accessing a sustring from a gi'en string@ SE:S$/I68)string,initial,length
2.Indexing& Also called pattern matching i!e! position where a string
pattern P first appears in agi'en string $!
@I6DF)te(t,pattern
3. Concatenation & string consists of characters of first string followed y
characters of 5ndstring!
S0GGS5
4. Length & the numer of characters in a string!
168$9)string
05/20/16 PDM MCA 17
-
7/26/2019 DS_notes
18/105
Word Processing
-ollowing operations are there&
Repacement& replacing one string in the te(t y
another!
@ /P1AC)te(t,pattern0,pattern5
Insertion & inserting a string in the middle of the
te(t!
@I6S/$)te(t,position,stringDeetion& deleting a string from the te(t
@D1$)$e(t,position,length
05/20/16 PDM MCA 18
-
7/26/2019 DS_notes
19/105
Arrays
Array 7 a collection of a fi(ed numer of componentswherein all of the components ha'e the same data type
#ne7dimensional array 7 an array in which the componentsare arranged in a list form
$he general form of declaring a one7dimensional array is&
dataType arrayName[intExp];
where intExpis any e(pression that e'aluates to apositi'e integer
-
7/26/2019 DS_notes
20/105
Declaring an array
$he statement
intnum[5];
declares an array numof 5components of thetype int
$he components are num[0], num[1],
num[2], num[3], and num[4]
-
7/26/2019 DS_notes
21/105
-
7/26/2019 DS_notes
22/105
Accessing Array
Components
$he general form )synta( of accessing an array component is&
arrayName[indexExp]
where indexExp, called index, is any e(pression whose'alue is a nonnegati'e integer
Inde( 'alue specifies the position of the component in the array
$he []operator is called the arra! subscriptingoperator
$he array inde( always starts at 0
-
7/26/2019 DS_notes
23/105
05/20/16 PDM MCA 23
-
7/26/2019 DS_notes
24/105
1in"ed 1ist
Definition of 1in"ed 1ists
(amples of 1in"ed 1ists
#perations on 1in"ed 1ists
1in"ed 1ist as a Class
1in"ed 1ists as Implementations of Stac"s, Sets, etc!
24/320PDM I$
-
7/26/2019 DS_notes
25/105
De"inition o" Lin#ed
Lists
A lin"ed list is a se2uence of items )o%ects where e'ery item is
lin"ed to the ne(t!
8raphically&
data data data data
head_ptr tail_ptr
25/320PDM I$
-
7/26/2019 DS_notes
26/105
De"inition Detais
ach item has a data part )one or more data memers, and alin" that points to the ne(t item
#ne natural way to implement the lin" is as a pointerH that is, thelin" is the address of the ne(t item in the list
It ma"es good sense to 'iew each item as an o%ect, that is, as aninstance of a class!
We call that class& 6ode
$he last item does not point to anything! We set its lin" memerto $%LL! $his is denoted graphically y a self7loop
26/320PDM I$
-
7/26/2019 DS_notes
27/105
&xampe o" Lin#ed List
'( )aiting Line*
A waiting line of customers& ohn, Mary, Dan, Sue )from the head to
the tail of the line
A lin"ed list of strings can represent this line&
John Mary Dan Sue
head_ptrtail_ptr
27/320PDM I$
-
7/26/2019 DS_notes
28/105
pointer to a
next node
pointer to
an eleent
node
!llu"tration o# a lin$ed li"t in eory%
28/320
-
7/26/2019 DS_notes
29/105
pointer to a
next node
pointer to
an eleent
node
29/320
-
7/26/2019 DS_notes
30/105
pointer to a
next node
pointer to
an eleent
node
30/320
-
7/26/2019 DS_notes
31/105
pointer to a
next node
pointer to
an eleent
node
31/320
-
7/26/2019 DS_notes
32/105
32/320
-
7/26/2019 DS_notes
33/105
Singly 1in"ed 1ists
and Arrays
33/320
-
7/26/2019 DS_notes
34/105
+perations on Lin#ed
Lists Inserta new item
@ At the head of the list, or
@ At the tail of the list, or
@ Inside the list, in some designated position
Searchfor an item in the list
@ $he item can e specified y position, or y some 'alue Deetean item from the list
@ Search for and locate the item, then remo'e the item, andfinally ad%ust the surrounding pointers
si,e) H is&mpt!)
34/320PDM I$
-
7/26/2019 DS_notes
35/105
Insert (t the ead
Insert a new data A! Call new/ newPtr 1ist efore insertion&
After insertion to head&
data data data data
head_ptr tail_ptr
&
data data data data
head_ptr tail_ptr
&
'(he lin$ )alue in the ne* ite + old head_ptr
'(he ne* )alue o# head_ptr + ne*,tr
35/320PDM I$
-
7/26/2019 DS_notes
36/105
Insert at the 0ai
Insert a new data A! Call new/ newPtr1ist efore insertion
After insertion to tail&
data data data data
head_ptr tail_ptr
&
data data data data
head_ptr tail_ptr
&
'(he lin$ )alue in the ne* ite + -.
'(he lin$ )alue o# the old la"t ite + ne*,tr
36/320PDM I$
-
7/26/2019 DS_notes
37/105
Insert inside the List
Insert a new data A! Call new/ newPtr1ist efore insertion&
After insertion in rdposition&
data data data data
head_ptr tail_ptr
data
data & data data
head_ptr tail_ptr
data
'(he lin$)alue in the ne* ite + lin$)alue o# 2ndite
'(he ne* lin$)alue o# 2ndite + ne*,tr
37/320PDM I$
-
7/26/2019 DS_notes
38/105
Deete the ead Item
1ist efore deletion&
1ist after deletion of the head item&
data data data data
head_ptr tail_ptr
data data data data
head_ptr tail_ptr
data
'(he ne* )alue o# head_ptr + lin$)alue o# the old head ite
'(he old head ite i" deleted and it" eory returned
data
38/320PDM I$
-
7/26/2019 DS_notes
39/105
Deete the 0ai Item
1ist efore deletion&
1ist after deletion of the tail item&
data data data data
head_ptr tail_ptr
data data data
head_ptr tail_ptr
'-e* )alue o# tail_ptr + lin$)alue o# the 3rd#ro la"t ite
'-e* lin$)alue o# ne* la"t ite + NULL
data
datadata
39/320PDM I$
-
7/26/2019 DS_notes
40/105
Deete an inside Item
1ist efore deletion&
1ist after deletion of the 5nditem&
data data data data
head_ptr tail_ptr
data data
head_ptr tail_ptr
'-e* lin$)alue o# the ite loated e#ore the deleted one +
the lin$)alue o# the deleted ite
data
data datadata
40/320PDM I$
-
7/26/2019 DS_notes
41/105
Impementation o"
Lin#ed List
A lin"ed list is a collection of 6ode o%ects, and must support a
numer of operations
$herefore, it is sensile to implement a lin"ed list as a class
$he class name for it is List
41/320PDM I$
-
7/26/2019 DS_notes
42/105
Circular 1in"ed 1ist
In linear lin"ed lists if a list is tra'ersed )all the elements 'isited ane(ternal pointer to the list must e preser'ed in order to e ale toreference the list again!
Circular lin"ed lists can e used to help the tra'erse the same listagain and again if needed! A circular list is 'ery similar to the linearlist where in the circular list the pointer of the last node points not
6E11 ut the first node!
42/320PDM I$
-
7/26/2019 DS_notes
43/105
Contd!
A Linear Linked List
43/320PDM I$
-
7/26/2019 DS_notes
44/105
Contd!
44/320PDM I$
-
7/26/2019 DS_notes
45/105
Contd!
45/320PDM I$
-
7/26/2019 DS_notes
46/105
Circular 1in"ed 1ist
In a circular lin"ed list there are two methods to "nowif a node is the first node or not!
@ither a e(ternal pointer, list, points the first node
or@A header node is placed as the first node of thecircular list!
$he header node can e separated from the others y
either hea'ing a sentinel value as the info part orha'ing a dedicatedflag 'ariale to specify if the node
is a header node or not!
46/320PDM I$
-
7/26/2019 DS_notes
47/105
Douly 1in"ed 1ist
A doule ended is 2ueue where we can do the
insertion and deletion at oth the front and rear
ends
47/320PDM I$
-
7/26/2019 DS_notes
48/105
Contd!
48/320PDM I$
-
7/26/2019 DS_notes
49/105
Implementation
49/320PDM I$
-
7/26/2019 DS_notes
50/105
Stac"s
A stac" is a list of elements in which anelement may e inserted or deleted only at one
end, called the top of the stac"!
$he elements are remo'ed from a stac" in there'erse order of that in which they were
inserted into the stac"!
Stac" is also "nown as a 1I-# )1ast in -astout list or Push down list!
-
7/26/2019 DS_notes
51/105
:asic Stac" #perations
%S& It is the term used to insert an elementinto a stac"!
,.S operation" on "ta$
-
7/26/2019 DS_notes
52/105
:asic Stac" #perations
+& It is the term used to delete an element
from a stac"!
,, operation #ro a "ta$
-
7/26/2019 DS_notes
53/105
Standard rror Messages
in Stac"
$wo standard error messages of stac" are
@Stac# +er"ow& If we attempt to add new element
eyond the ma(imum size, we will encounter a
stack overflowcondition!@Stac# %nder"ow& If we attempt to remo'e
elements eyond the ase of the stac", we will
encounter astack underflowcondition!
-
7/26/2019 DS_notes
54/105
Stac" #perations
PES9 )S$ACJ, $#P, MAFS$/, I$M& $his procedure pushes
an I$M onto a stac"
0! If $#P K MAFSIL, then Print& #4/-1#W, and /eturn!
5! Set $#P &K $#P 0 NIncreases $#P y 0O
! Set S$ACJ N$#PO &K I$M! NInsert I$M in $#P positionO
! /eturn
P#P )S$ACJ, $#P, I$M& $his procedure deletes the top
element of S$ACJ and assign it to the 'ariale I$M
0! If $#P K Q, then Print& E6D/-1#W, and /eturn!
5! Set I$M &K S$ACJN$#PO
! Set $#P &K $#P 7 0 NDecreases $#P y 0O
! /eturn
-
7/26/2019 DS_notes
55/105
Applications of Stac"
Con'erting algeraic e(pressions from one
form to another! !g! Infi( to Postfi(, Infi( to
Prefi(, Prefi( to Infi(, Prefi( to Postfi(,
Postfi( to Infi( and Postfi( to prefi(!
'aluation of Postfi( e(pression!
Parenthesis :alancing in Compilers!
Depth -irst Search $ra'ersal of 8raph!
/ecursi'e Applications!
-
7/26/2019 DS_notes
56/105
(gebraic &xpressions
In"ix/It is the form of an arithmetic e(pression in which
we fi( )place the arithmetic operator in etween the twooperands! !g!& )A : R )C 7 D
re"ix/ It is the form of an arithmetic notation in which
we fi( )place the arithmetic operator efore )pre itstwo operands! $he prefi( notation is called as polish
notation! !g!& R A : @ C D
ost"ix/ It is the form of an arithmetic e(pression in
which we fi( )place the arithmetic operator after )postits two operands! $he postfi( notation is called as suffix
notationand is also referred to reverse polish notation!
!g& A : C D 7 R
-
7/26/2019 DS_notes
57/105
Conersion "rom In"ix to ost"ix
on)ert the #ollo*in in#ix expre""ion & : ; D / < : into it" e=ui)alent
po"t#ix expre""ion
& ti " t"i
-
7/26/2019 DS_notes
58/105
&auation o" ost"ix
&xpression
Postfi( e(pression& T 5 U R R
-
7/26/2019 DS_notes
59/105
ueue
A 2ueue is a data structure where items areinserted at one end called the rear and deleted
at the other end called the front!
Another name for a 2ueue is a
-
7/26/2019 DS_notes
60/105
Representation o"
ueue!nitially the =ueue i" epty
-o*> in"ert 11 to the =ueue (hen =ueue "tatu" *ill e%
-ext> in"ert 22 to the =ueue (hen the =ueue "tatu" i"%
Representation o"
-
7/26/2019 DS_notes
61/105
Representation o"
ueue-o*> delete an eleent 11
-ext in"ert another eleent> "ay 66 to the =ueue ?e annot in"ert 66 to the
=ueue a" it "inal" =ueue i" #ull (he =ueue "tatu" i" a" #ollo*"%
ueue +perations using
-
7/26/2019 DS_notes
62/105
ueue +perations using
(rra!
4arious operations of 3ueue are&@insert'*/ inserts an element at the end of 2ueue 3!
@deete'*/ deletes the first element of 3!
@dispa!'*/ displays the elements in the 2ueue! $here are two prolems associated with linear
2ueue! $hey are&
@0ime consuming& linear time to e spent in shiftingthe elements to the eginning of the 2ueue!
@Signaing ueue "u& e'en if the 2ueue is ha'ing
'acant position!
-
7/26/2019 DS_notes
63/105
-
7/26/2019 DS_notes
64/105
Circuar ueue
A circular 2ueue is one in which the insertionof new element is done at the 'ery first
location of the 2ueue if the last location of the
2ueue is full!
Suppose if we ha'e a 3ueue of n elements
then after adding the element at the last inde(
i!e! )n70th , as 2ueue is starting with Q inde(,
the ne(t element will e inserted at the 'ery
first location of the 2ueue which was not
possile in the simple linear 2ueue!
Circular 3ueue
-
7/26/2019 DS_notes
65/105
Circular 3ueue
operations $he :asic #perations of a circular 2ueue are
@InsertionC& Inserting an element into a circular
2ueue results in /ear K )/ear 0 V MAF, where
MAF is the ma(imum size of the array!
@DeetionC& Deleting an element from a circular2ueue results in -ront K )-ront 0 V MAF,
where MAF is the ma(imum size of the array!
@0raersC& Displaying the elements of a circular3ueue!
Circular 3ueue mpty& -rontK/earKQ!
Circular 3ueue
-
7/26/2019 DS_notes
66/105
/epresentation using
Arrayset u" on"ider a irular =ueue> *hih an hold axiu @M&AB o# "ixeleent" !nitially the =ueue i" epty
Insertion and Deletion operations on a
-
7/26/2019 DS_notes
67/105
Insertion and Deletion operations on a
Circular 3ueue!n"ert ne* eleent" 11> 22> 33> 44 and 55 into the irular =ueue (he irular
=ueue "tatu" i"%
-o*> delete t*o eleent" 11> 22 #ro the irular =ueue (he irular =ueue
"tatu" i" a" #ollo*"%
Insertion and Deletion operations on a
-
7/26/2019 DS_notes
68/105
Insertion and Deletion operations on a
Circular 3ueue&ain> in"ert another eleent 66 to the irular =ueue (he "tatu" o# the irular
=ueue i"%
&ain> in"ert 77 and 88 to the irular =ueue (he "tatu" o# the irular =ueue
i"%
Doule nded 3ueue
-
7/26/2019 DS_notes
69/105
Doule nded 3ueue
)D3E
It is a special 2ueue li"e data structure thatsupports insertion and deletion at oth the front
and the rear of the 2ueue!
Such an e(tension of a 2ueue is called adoube-ended ueue5 or deue5 which is
usually pronounced 6dec#6 to a'oid confusion
with the de2ueue method of the regular 2ueue,
which is pronounced li"e the are'iation
6D..6
It is also often called a head-tai in#ed ist!
D3E /epresentation
-
7/26/2019 DS_notes
70/105
D3E /epresentation
using arrays
-
7/26/2019 DS_notes
71/105
$ypes of D3E
$here are two 'ariations of de2ue! $hey are&@Input restricted de2ue )I/D
@#utput restricted de2ue )#/D
An Input restricted de2ue is a de2ue, whichallows insertions at one end ut allows
deletions at oth ends of the list!
An output restricted de2ue is a de2ue, whichallows deletions at one end ut allows
insertions at oth ends of the list!
i i
-
7/26/2019 DS_notes
72/105
riorit! ueue
A priority 2ueue is a collection of elementsthat each element has een assigned a priority
and such that order in which elements are
deleted and processed comes from the
following riles&
@An element of higher priority is processed efore
any element of lower priority!
@$wo element with the same priority are processedaccording to the order in which they were added to
the 2ueue!
-
7/26/2019 DS_notes
73/105
Priority 3ueue #perations and Esage
Inserting new elements! /emo'ing the largest or smallest element!
Priority 3ueue Esages are&
@Simuations/ 'ents are ordered y the time atwhich they should e e(ecuted!
@7ob scheduing in computer systems& 9igher
priority %os should e e(ecuted first!@Constraint s!stems/ 9igher priority constraints
should e satisfied efore lower priority constraints!
$ree terminology and
-
7/26/2019 DS_notes
74/105
$ree terminology and
defination
Composed of nodesand edges
Node@ Any distinguishale o%ect
Edge@ An ordered pair
-
7/26/2019 DS_notes
75/105
Contd!
0! A single node, with no edges, is a tree! $heroot of the tree is its uni2ue node!
5! 1et "#, , "k)k XK0 e trees with no nodes
in common, and let r0, ,r"e the roots ofthose trees, respecti'ely! 1et re a new node!$hen there is a tree $ consisting of the nodesand edges of "#, , "k, the new node r andthe edges
-
7/26/2019 DS_notes
76/105
Contd!
ris called theparentof r#, $, rk
r#, $, rkare the childrenof r
r#
, $, rk
are the silingsof one another 6ode ' is a descendantof u if
@u % v or
@vis a descendant of a child of u@A path e(ists from uto v!
76/320PDM I$
-
7/26/2019 DS_notes
77/105
$ree $erminology
'ery node is a descendant of itself!
If vis a descendantof u, then uis an ancestorof v!
Properdescendants&@$he descendants of a node, other than the node
itself!
Proper ancestors@$he ancestors of a node, other than the node itself!
77/320PDM I$
-
7/26/2019 DS_notes
78/105
properties
1eaf
@a node with no children
6umYnodes K 6umYedges 0
@'ery tree has e(actly one more node than edge
@'ery edge, e(cept the root, is the head of e(actly
one of the edges
78/320PDM I$
-
7/26/2019 DS_notes
79/105
$ree $erminology
9eight of a node in a tree
@1ength of the longest path from that node to a leaf
Depthof a node in a tree
@1ength of the path from the root of the tree to the
node
79/320PDM I$
$ree terminology
-
7/26/2019 DS_notes
80/105
$ree terminology
w has depth 5
uhas height
tree has height u
w
80/320PDM I$
-
7/26/2019 DS_notes
81/105
$rees
A tree is a collection of nodes
@$he collection can e empty
@)recursi'e definition If not empty, a tree consists
of a distinguished node r )the root, and zero ormore nonemptysubtrees$0, $5, !!!!, $", each of
whose roots are connected y a directed edgefrom
r
81/320PDM I$
-
7/26/2019 DS_notes
82/105
Some $erminologies
&hildandparent
@ 'ery node e(cept the root has one parent
@ A node can ha'e an aritrary numer of children
'eaves
@ 6odes with no children
ibling
@ nodes with same parent
82/320PDM I$
-
7/26/2019 DS_notes
83/105
Some $erminologies
ath
'ength*numer of edges on the path
+epthof a node
@ length of the uni2ue path from the root to that node
@ $he depth of a treeis e2ual to the depth of the deepest leaf
eightof a node
@ length of the longest path from that node to a leaf
@ all lea'es are at height Q
@ $he height of a treeis e2ual to the height of the root
Ancestorand descendant
@ roper ancestorandproper descendant
83/320PDM I$
(ample& E6IF
-
7/26/2019 DS_notes
84/105
(ample& E6IF
Directory
84/320PDM I$
i
-
7/26/2019 DS_notes
85/105
:inary $rees
A tree in which no node can ha'e more than two children
$he depth of an
-
7/26/2019 DS_notes
86/105
Contd!
An ordered tree with at most two children for
each node
If node has two child, the 0stis called the left
child, the 5ndis called the right child
If only one child, it is either the right child or
the left child
86/320PDM I$
(ample& (pression
-
7/26/2019 DS_notes
87/105
(ample& (pression
$rees
1ea'es are operands )constants or 'ariales
$he other nodes )internal nodes contain operators
Will not e a inary tree if some operators are not inary
87/320PDM I$
$ l
-
7/26/2019 DS_notes
88/105
$ree tra'ersal
Esed to print out the data in a tree in a certain
order
Pre7order tra'ersal
@Print the data at the root
@/ecursi'ely print out all data in the left sutree
@/ecursi'ely print out all data in the right sutree
88/320PDM I$
Preorder, Postorder
-
7/26/2019 DS_notes
89/105
eo de , osto de
and Inorder
Preorder tra'ersal@node, left, right
@prefi( e(pression
aRcRRdefg
89/320PDM I$
Preorder, Postorder
-
7/26/2019 DS_notes
90/105
,
and Inorder
Postorder tra'ersal@left, right, node
@postfi( e(pression
acRdeRfgR
Inorder tra'ersal@ left, node, right!
@ infi( e(pression aRcdRefRg
90/320PDM I$
:i $
-
7/26/2019 DS_notes
91/105
:inary $rees
Possile operations on the :inary $ree AD$@ parent
@ leftYchild, rightYchild
@ siling
@ root, etc Implementation
@ :ecause a inary tree has at most two children, we can "eep direct
pointers to them
91/320PDM I$
8 h
-
7/26/2019 DS_notes
92/105
8raph
A graph -is defined as follows&
-%(,E)
(-)/a finite, nonempty set of 'ertices
E(-)/a set of edges )pairs of 'ertices
Directed 's! undirected
-
7/26/2019 DS_notes
93/105
graphs
When the edges in a graph ha'e no
direction, the graph is called undirected
Directed 's! undirected
8 h t i l
-
7/26/2019 DS_notes
94/105
When the edges in a graph ha'e a direction,the graph is called directed)or digraph
graphs )cont!
3B @3>1B @5>9B @9>11B @5>7B
0arning& if the graph is
directed, the order of the
'ertices in each edge isimportant ZZ
8raph terminology
$ h
8 h t i l
-
7/26/2019 DS_notes
95/105
$rees are special cases of graphsZZ
$rees 's graphs8raph terminology
8 h t i l
-
7/26/2019 DS_notes
96/105
8raph terminology
Ad%acent nodes& two nodes are ad%acent if they areconnected y an edge
Path& a se2uence of 'ertices that connect two
nodes in a graph
Complete graph& a graph in which e'ery 'erte( is
directly connected to e'ery other 'erte(
5 i" adEaentto7
7 i" adEaent #ro5
8raph Properties 77 Paths
-
7/26/2019 DS_notes
97/105
07[\
and Connecti'ity
Paths@ A path from 'erte( u to ' of a graph 8 is defined as a se2uence of
ad%acent )connected y an edge 'ertices that starts with u and ends with'!
@ Simple paths& All edges of a path are distinct!
@ Path lengths& the numer of edges, or the numer of 'ertices @ 0! Connected graphs
@ A graph is said to e connected if for e'ery pair of its 'ertices u and 'there is a path from u to '!
Connected component
@ $he ma(imum connected sugraph of a gi'en graph!
8 h t i l ) t
8raph terminology
-
7/26/2019 DS_notes
98/105
What is the numer of edges in a completedirected graph with 6 'ertices]
N 1 (N*#)
8raph terminology )cont!
5) ,2 N
8raph terminology
8 h t i l ) t
8raph terminology
-
7/26/2019 DS_notes
99/105
What is the numer of edges in a completeundirected graph with 6 'ertices]
N 1 (N*#) 3 4
8raph terminology )cont!
5
) ,2 N
8raph terminology
8raph terminology
-
7/26/2019 DS_notes
100/105
Weighted graph& a graph in which each edgecarries a 'alue
8raph terminology )cont!8raph terminology
8 h i l i
-
7/26/2019 DS_notes
101/105
8raph implementation
Array7ased implementation@A 0D array is used to represent the 'ertices
@A 5D array )ad%acency matri( is used to
represent the edges
Array7ased
i l i
-
7/26/2019 DS_notes
102/105
implementation
8raph implementation
-
7/26/2019 DS_notes
103/105
p p
)cont!
1in"ed7list implementation@A 0D array is used to represent the 'ertices
@A list is used for each 'erte( vwhich contains the
'ertices which are ad%acent from v )ad%acency list
1in"ed7listimplementation
-
7/26/2019 DS_notes
104/105
implementation
Ad%acency matri( 's!ad%acency list
-
7/26/2019 DS_notes
105/105
ad%acency listrepresentation
(d8acenc! matrix@8ood for dense graphs 77E_2)^5
@Memory re2uirements& 2)^4^ E5 K #)^5
@Connecti'ity etween two 'ertices can e tested2uic"ly
(d8acenc! ist
@8ood for sparse graphs 77 E_2)^@Memory re2uirements& 2(55 6 5E5)%2(55)
@ 4ertices ad%acent to another 'erte( can e found