0 ratings 0% found this document useful (0 votes) 75 views 53 pages Graph or Tree Data Structure
The document outlines various algorithms and procedures for binary tree operations, including insertion, deletion, and traversal methods such as preorder, inorder, and postfix expressions. It provides examples of searching for nodes within binary search trees and discusses the structure of AVL trees and M-way search trees. Additionally, it explains the process of balancing trees through rotations and the significance of maintaining tree properties during operations.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save graph or tree data structure For Later Proceed down ihe lft most path rooted at PTR = F. Push the node F ong
STACK : 9, A, 0, -G, EF
8 Proceed down the lft most path rooted at PTR = G. PUSH the node G onta
stack. Therefore,
STACK: 6, A, 0,6
% (a) POP and process G
(©) POP and process D
(6) POP and process A
() POP Null and theretore we exit rom the algorthm,
in his example, nodes are processed inthe following order:
CBFEG.DAPloune saa
cad AVE carat. M8 Ct eeniom to untilered AVL serch ve ran
Daieod AVE each ec essen a——— i
\
\
\
S :
. " |
Joon Repeat white Lem \
wrt eal o lon we have 1 wa poceGU 5:2 ancy | ba
Fem rear ot Sion case2 and Procedure 53 rte watt ss mm
Gcseed above 3 Tans wo,
= exis» EASEAB(WFO. PTR TR, ROOT, LO, PAR) { adie oe
3 7 f, LOC, PAR) \
|. The procedure delete the node (N) at location LOC. The pointer i
| Jpeprccede dit only cd of N otherwise CHILD = WIAD
|, Inaeate mat W nas no chen.
| stp 1 ntatzs be pointer CHILD}
I! If LPTR [LOC] := NULL and RPTR [LOC] :=NULL then,
I ‘Set CHILD := NULL
Else PTR [LOC] < > NULL then
Set CHILD == RPTR [LOC]
‘Set CHILD := LPTR [LOC]
Now we can write the deletion algorthon 95Pau a
see 1: the Key i892 terminal node ty
ca en
fotete fh, Node is changed 0 as show mig 3 e587) SO: For example To
Ss
[ro] [ps 35 |40
fe] Pops) Be]
(g) Inserting 35
(0 Spitting the root node afer iaetn
50 Into a leat node
FIGURE 5.81
‘Case 2: If the key is notin terrinat node, ts replaced by ts successor, hate 8
key with a next higher value, and deleted. For example, on deletion te Key fom
figure 5.64, we obtainnee presen Vean hap hae
Tomlcn ae uauay teu Waee.
6.1.1.3 Postfix Expression
Example 2
Make a expression tree for the folowing expression,
(arbre) (ave)
‘ite Profix, infix and Post expcesson trom the expression tee.
Solution :
‘The expression tree has been consiucted using the order of precedence
‘associativity laws of arthmetic operators. Expression tree for the Given expres
is shown in figure 5.20, ]so at upicate Hers ae ne
Nery 80a 108 Tm very gen ON BSy
en Ex: i
.10 Searching and Inserting in Rey
pose Tis a binary search
ordre etna
(iy) We meet an er
wri
Example 8
Consider the binary search trea T shown in figure 528. Suppose ITEM = 37.
Now steps are
(1) Compare the value 37 with 40 and we find that 37 < 40, therelore, proceed
to the left child of 40, which is 32.
(2) Compare the value 37 with 32. Since 37 > 2, therelore, proceed to the right
child of 32, which is 35,
(3) Compare the value 37 with 35. Since 37 > 35 and 35 does not have a Aight
Child, insert 37 as the right child of 35, 4‘Since. conse of nodes woich can have at most two
Othe odes used knked representation is PAB. So on,
[fete [neo [rete
Where _LPTR denote the addresses or locations of let subtreas
PTR denote the adcressos or locations of right subtres,
INFO species the information contents of a node,
Empty sutirees are represented by a pointer value of NULL.
For example, consider the BT. Shown in Figure 5.13,“The preorder traversal tab
re ere oo, Ror ect as ows
link is NULL as se
oUFE S18
Preorder f the Binary ree is
ABCODEFG
“The inorder traversal of binary reo is given by he fotlweng saps =cone i ety
= 8
stealer an arent A yom won
Soto an agen
sonverse Preorder)
ression
15. Using nore te un,
vere met,
70, -, 40 en
an inherent
From fig. 5.18, USing poster reversal met, wo gt
50, 6,", 70, 40, 5+
Which is 8n expression in postfix notation,
Example 2
Make a expression tree forthe folowing expression.
(arbre) | (dee)
Write Prefix, infix and Postix expression rom the expression es.
ROURE 518 eae
The terminal nodes (leaves) of an expression tre are the variables or co : sei it precedence
a wd
{Pe expression. The no-terminal nodes of an expression tree are the operaion\fe Te expression tree has been Ses ane once
ANd 9) Notice ate parenteses wich appear in Expression donk cnonciab i Sone sae
‘is shown in figure 5:20, (8
|ca prea \
| step 4 Armee rot ane) \
| NRTA <> ue ee \
| Ext
| $2 [rraverge tne let subtree]
i MLPTA (F) <> NULL then
I call INORDER (LPTR (R))
| $23 [Process the root node}
Example 3
WRITE (INFO (R)) Draw the diagram ot a binary tee Tit the preorder and inorde Taverna ot
} ‘Stop 4 (Traverse the right subtree] veld the following sequences of nodes:
? WAPTR (A) <> NULL then
Promo: G@ B Q@ Ac P bE AR
call INORDER (RPTR (R))
moder: =9@ 8B C A G P € DRconned yada be trade Pay
oune sz
Lot us traverse this binary tree using stack.
1. Initially, PUSH NULL (0.6) onte STACK and set. PTR = ROOT. Tharelore,
STACK :
PTR: = A, the root of binary tree.
2 Proceed down the let most path rocted at PTR = A as follows =
(a) Process A and PUSH its right chid D onto STACK. Theretore
‘STACK :¢,0
(>) Process B (Note that there is no right child),
(©) Process € (Nate nat there is no tight hil)
5.7.1 Preorder Traversal
Algorithm
Inltety push NULL onto STA
‘si9p6 unt PTR = NULL or
‘CK and then set PTR'= ROOT: Now repeat the following
‘quivalenty, while PTR 2NULL.
(184)\
33 8, "
@) @ &)
%5 2, ,
“ @ © © a tensa Tr
‘Sot PTR := LPTR PTR] and TEMP := PTR. |
Q @ Q Loe
SR SR SKB
@0O 6 © OO
© a ¢
FIGURE 5.20ton
twee in memory and we \
oS wana
to each of is nodes using pr S00 mn operon PROCESS |
‘mera TOP etm pr ot
Ke.
fight child F onto STACK Theretore
STACK: 9.6.F
Now, thero iso other let childs procesed.
5. POP te op element of stack and assign to PTR, Therelore,
\
+ \
ks \
\
7. POP the top element of stack and assign to PTR, Therefore x
XF LPTR (PTR = NULL then \
‘Set PTR : = LPTRIPTRL ‘
‘ELSE \
‘Since PTA NULL, therfore, repeat the process. [POP From STACK) \
8 Proceed down the left most path rooted at PTR : = G. as follows. ‘get PTR : = SITOP] ;
(@) Process G (Note that there is no right child) JORSRTOR =A
Now, there is no other left child is processed. ead anne
9% POP the top element of stack and assign to PTR. Theretore [End of stop 2 while loop
PTR: = NULL. ‘Step 6 {Finished}
‘Since PTR = NULL, Therelore we ext from the algorithm,Fs SAORI Ai a=
LPTR [NEW] :=NULL and
RPTR (NEW) = Ni
Step 4 [Add ITEM to tree}
Etselt ITEM < INFO
| Set RPTR [PA
{End of t Structure}
$-11 Deletion form a Binary Se
Suppose T is a binary sea .
(Assume we want
locaton of node N which
‘48ing the previous Proced
PAR = NULL then
i ‘Set ROOT s= NEW
‘Set LPTR [PAR] := NEW
S Oe" ba,
PTH, PTR, ROOT, ITEM, Log,
uu
[PAR] Then
A] = NEW
‘arch Tree
"an
case)
‘FIGURE 52 (AFTER DELETION OF THE NODE Bo
Case 3:
the node N tobe deleted has both he chikren. inthis cas, we have to chan Sate
Inorder (or any traverser) successor SIN) ofthe node to be deleted. Then M
{& deleted from T by fist deleting 1) tom T and hen replacing N by nod S(N)
Note that we have to follow the case} or case 2 to delete SiN), For example
|e want to delete 22 from the binary search tee shown inf 5:32. Cheer at ex
‘35s the inorder successor of node 2. 5.33 shows etree after deletion of nade 32.
(200)noose eter te TGS hoi
Por the smallest ofthe Key clement!
replace K. As mentioned betor®, to move
replacements and deletions.
‘AB - treo is also known on balance sor tree
smalledst of the keys trom the node | . me
Figure 5.59 shows the deletion of 40. ‘5.16.1 Searching the B-Tree
‘Suppose we want o search ne node 50 Some nea te
atthe root. eeicion| gu begin
‘Since 20 < 56, it must be in the subtree tothe let of $8. Since 20s larger than 18.
‘and less than 26, it must be in the subtree tothe right of 18 and tothe lft of 28. we
‘then find that the node containing 20 is locate inthe toot ofthis subtree.90) tea
fom nears teat 24 Ma Po man wg in
‘wo minum wold as sown tect MOR ate Sam ch
ces ‘oe
i step 28 removed trom th fel ano naw parent no,
hee Wand 1 arene woth 2nd Pall OO ‘with weight 12, is inserted into the et So row the sorted at by weit
‘example, considar he 2100 cot 0 eg F
wo 2 $s as 7
‘step 3 Repeat the loop, combining he two minimum weights data toms. THs
result in:
®
ARO
(ay (al
Tho weighted path length of 2-tree as shown in figure 5.69 is
P=22+33+55+72+92 ‘RQURE S71
#4494154 14418
=60'S called @ Sequence sat. There B-tree has wo parts,
The index partis the interior nodes.
(The sequence setis the leaves.
(ioot MMM TS a
[Now the lists just one element 4
igure 5.74 te.docred Muaman veg nt Hence ha tee stun
Wi Mi Me — My
‘Also, inthe T’ replace the extemainade ww, bythe ‘
\
\
Step 3 Repeat step 1 ‘and stop 2 unt there is only one weight
left in the list \
\
\
\
1
\
\
\
\
\
\
\
\
1‘¢3 Deletion in an Mt
0 meena Te
a
‘mQURE 556
insert
‘Again, sypposo wo want 10
110.15] 10 Insert 8. But this node
Bint tas shown in fig, 5.55.
5
se Meee erable,
‘case 2: If(P, * NULL P
18 Using searching algorithm, we get the.
uit hence we open a new child Node ang
ms
late 15, wo src or
na tetloe, simpy dle e
cage 2:10.7 MUL “NIA er ore ea dewey oan
oon ee
Aoson of may calor seagate et seep yey
Siar manner enable heap ne
For SRE ls Sa SEB va,
oer the cna. « ML wah NA enc wc an
largo nba cne «WAL as
357 shows the deiebon sr at ch Nec me(or M-wary) 58m
5.15 Multiway (or Mama
Tras tt beaec Ein te 7008 YO we Koop
eon
Sante ay a or
ee. vous
ron nr pave vas DOneea” a : mmene hal
1st Searching in an May
SEE eae SSE
ry earch
e's sorta inary seach res.
Example 13,
Search fr 35 in Sway seach
We shown in
Compa the val 36, ose 5.2 step ae
to tho second subtest 95-30, and 3540, theratore, move down
2. lhe second substi node 35
‘he second subvee ot tana 4 26<34, mereore, move down to
3. Search is sucnessu, because 35 i. iaaumad
Example 14
‘Search for 70 in -way search ee shown in gure $52 saps are:
1 ‘Compare the value 70 at the root, 70>40, theretore, move down the third
binary Search tree is a 2 - way tree. | en
Now we can define M-way search trees, An m-way search tree is a tree jn c
‘each node has out-degree 60,theretore, move doy the nid sutiree ofthis node. Bu there
“is'@ NULL porter atthe postion ofthe thie sto. Therefore, seh
_unsuccesstul,
| gn ee 3 ray
§.15.2 Insertion is an M-way search tree \
To insert a new element into an M-way tree we proceed in the same way a= 0
‘would in order to search for the node. For example, to insert 25 ito ww
‘search tree shown in fig 5.52, we proceed to search for 25
| the tree at the node [20] wit the second child node showing
\Oo @
aimed A Sa
PoURE a
since BF of one of the nodes
crn WR Tl We bar om OPS al eat ee
(4) RL rotation
RL is similer to LR rotation. RL. rotation is also known as double rotation,
[RL rotation we perform first right rotation at some node (say A) and seca
lett rotation at another node (say B),
Example 11
‘Constnict a height balanced tree or AVL. tree using the folowing elements in ox
2.6.9,14, 12,16
We begin at the root of the tree since the tree I intially empty: We have
(214)5% ing an AV
reps a AVL soar
Segue ee fo an arr nat
Yat a mae
Now wo may define a Sana Ba
tow ay sree Hog ht ee)
same height
re then BF = 0
(__ttleh Subtree is higher than BF = +4 :
m,. camoamcnnta te
Fre 5:35 shows a Height balance tree having a Balance
et{Repeat for each element to be placed in heap]
Fopeat Stop 210 Stap 7 for COUNT = 210 N
{Obtain child to be ploced at heap level]
‘Now algorithm for the Heap Sorts an folow. Note that each stepis sof explanatory Po | BR
(208)[88
Q @ Q
go-§6 6 2 ®
66066 660
Tanase
(Operation on the Heap
®
G @ a
6 ® OTE
@)
GRO)
© ®
‘Now reconstruct the heap, we obtains
Lo
insert ai AS), Hence A(5]=21. Now place the
positon and recon We Nea, wo occ
Alter remove the node 21 andi
‘St element 13 in the ist
jee
AY
‘Alter romoving the Root node (25) ofthe heap and unsent this element my
‘Al Where A is name of sorted lst. Hence AJ6]=25. We placed the las
(208)
Flemove the node 13 and inswent at 2 We cian te heap
Sone
® Leen
Finally we insert the last element at At] and we obtain the sorted iat
Sorted lst
bests pees]
Complexity of Heap Sort zs.
‘number of comparisons in Heap Sort are O(n tog, 1), Heap Son
ieeaing mod wecmie as these Dent case, eae be nd Wrst
case performances. ry
i20h with 4 nodes A B,C, D and 4 edges :
[C.D}, (A.0} Therefore
Vertex Sot V
(A, B, 0, D)
Edge Set E (AB), {B,C}, (C.D), (A.D) )
= {AB, BC, CD, AD}
The see epee
Sao sae pct
(i) Order of @ graph, —
Path :
‘A walk between,
oFa9h
te
Sin nee ween
cinsap Peon as toe tn
seats
‘such that u =,
(@)
©)
©)
‘Simple Path : The path P is sai to be simple i all the nodes are
Gistinct, with the exception that v, may equal,
Cycle: A cycle is a closed simple path with longi 3 or more, A oyce
‘of length m is called m - cycleact org 2 Kom BoE (a,
Race wanes
|
sg ron ag
Peereerprenten
Serre sanseA
~~ are said to be
cue nh pn wa 1M
shown in ig 6.3 acyche
Distinct edges e and e' are called multiple edges if they connect the sang
‘endpoints, that is @ = [u, v] and e' = [u.v)
(9) Loops :
‘An edge eis called loop i thas identical endpoints that ise = (uu)
(*)—Muttigraph :
szohe that have mutole edges are known as muligraph as shown ni,
4. We wil not ciscuss mutiraph or raph with loops in these chapter
(235)oneeate
posenbeneten ee
verloce. are ©) Aneogeisicet ations sean
wT. omy wh oan,
ey
purse ®
geen F825
wight fan eg@ 9 fi
n this edge Belong to all grey
oy
1m Spanning Trees (MST)
sone
sine aa
or eee aaa
anne
A ‘spanning re can be used 1 approximately so th
aaaeeerreniem, A convenient formal way of dining this pence) ily, we ray consider the edges be de, Uc, ab ce, and or
snd to shortest path that vss each point at least once, inclusion in the tee as thei ost sequence conesponds to, 6,10, 11,18, 18,18
CatioTV company ayng cable toa city uses minimum spanning yf 19,21 and'23.
(a) Include the edges be and ba in
69.3 Algorithm of Minimum Spanning Tree (MST) (e) _Do:nat inclu th edge dea vera avast amet in.
> oe of MST. © Include the edge bt in T ~
rss Algoritm are ready connec
(©) Pris Algorithm (6) Doretincade he gets vari or
. ilea
ara
BE ica
ees eee eee
poe
gan oes ee
corect.
‘Message Signing
Dita sgnasres ae very common now-a-days. One characterise of nog
digial sgnatues is tat they work best on relatively short messages.
‘wanted 0 cigtally sign tis lesson, | woud tr 0 apply a digtal sgraan,
{0 he whole lesson. | would fn the hash value of the Zipped source tas
and sign the hash valve
tanyone subsequently altered the lesson, they could not forge my signature
he new hash (because they dont know my privat signing ka). Ay
‘reader who wished to check could easy discover that | had not signed te
‘modified lesson and would therelore be suspicious of it,
‘Many ea fe sources of random data are not quite as random as they realy
‘eed to be. They often 826 (for example, a source of random bis
‘ay tumbles data, ant can also inorease the degree
of randomness by compres
umber of truly random bag MP6" Of Sermi-random bits into a smaler
(288)
Tia otis aloo called vee slcion se. Touart on poss oka
knock-out or elimination tourament es typed to ogaze Song
‘matches, Pairwise competitions among players proceed ut wer
established. Let us consider one exarnge of
Example
‘Consider the following unsorted ist
1 18 1 4 19 4
uv 2 8Pass 10
Finally you obtain the two sorted ists.
10, 13, 14,15, 18,21, 28, 30
11,12
‘Morge both the ist to obtain the fnal sorte list
wou 2 3 1% 18 21 28 99
——_
‘ison of Soy
co a
From the table 2 itis clear that Selection Sor, Bubble Sort and te Insarton Sat
are O(n") Sante en oe ee
ee GN kee ener oo era
‘Hae Sot hve wort cae psa fe Foe oe
sco pelea sealtinures ait os
may Baty he panly sons renee is wale
Sort oF Quick Sort. Avoid Merge Sor when storage spa== —
‘Avoid Quick sort when the aay is nearly sorted,
my5 NO cont er
Some Oe ie Ewe c
a. Wester rom vert vers D and FS
esse rb ag miner and es
4 We proceed to vertce D, all the adjacent verticas have been cx
We consider lt-over verice B and add edge BC 10 the tree as shop,
figure. 6.31 |
ee ae
es aR nec
la hash function may map cstrinct hoy valves to the same areas Ths cabad
collision and it should be avoided as tar as possible, Charecersts of hashing
t'should evenly distribute the records to the avatable space,
Let us consider some hashing functions: