100% found this document useful (2 votes)
319 views141 pages

dsDay8WR PDF

The document provides an overview of data structures and algorithms. It outlines module prerequisites, the module plan which covers topics like time/space complexity, sorting, linked lists, queues, stacks, trees, and graphs. It then defines data structures and common ones like arrays, linked lists, stacks, and queues. It also discusses asymptotic analysis for analyzing time and space complexity, and provides examples of common time complexities like O(1), O(n), O(n^2), O(n^3), O(log n), and O(n log n).

Uploaded by

Saurabh Asalkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
319 views141 pages

dsDay8WR PDF

The document provides an overview of data structures and algorithms. It outlines module prerequisites, the module plan which covers topics like time/space complexity, sorting, linked lists, queues, stacks, trees, and graphs. It then defines data structures and common ones like arrays, linked lists, stacks, and queues. It also discusses asymptotic analysis for analyzing time and space complexity, and provides examples of common time complexities like O(1), O(n), O(n^2), O(n^3), O(log n), and O(n log n).

Uploaded by

Saurabh Asalkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 141

Data Structure & Algorithms

Sunbeam Infotech

Sunbeam Infotech www.sunbeaminfo.com


Module Pre-requisites

• Java Programming Language ✓


① thinking
• Language Fundamentals ② algorithms

• Methods ✓ ③ implementation
• Class & Object
④ interviews
• static members
• Arrays
• Collections
• Inner classes

Sunbeam Infotech www.sunbeaminfo.com


Module plan
1. Time & Space complexity - Problem Solving Techniques

2. Linear & Binary search - ① Divide & conquer

② Greedy approach
3. Recursion -

③ Dynamic Programming
4. Basic sorting -

5. Linked list -

Evaluations
6. Queues -

CCEE
① Theory - 40 marks -

7. Stacks-
② Lab -
40 marks

8. Trees-
③ Internal - 2d marks

9. Heap /

10. Advanced sorting -

11. Hashing -

12. Graphs -

Sunbeam Infotech www.sunbeaminfo.com


Data Structure
← Object oriented
• Data Structure • Data structures are ADT. -
-

• Organizing data in memory


• Processing the data } efficiently
ArrayAD
Ibstract Iata Iypes
random access

• Basic data structures ① get Me at index

• Array
-
② set Me at index

• Linked List
Stack ADT
-

: LZFO Queue ADT FZFO



:
Stack
-

÷ ÷
• Queue ② pop
-
② pop

• Advanced data structures ③ peek ③ peek


is
• Tree ④ Empty ④ is
Empty

=
• Heap
• Graph

Sunbeam Infotech www.sunbeaminfo.com


Data Structure

• Data Structure
✓ • Asymptotic analysis
-
I → canst K

• Organizing data in memory


• Processing the data } efficient
• It is not exact analysis
Big
hmm
0
/

^ → San
0cm)
→ Order of ↳
• Common data structures

hmmm n' → g
a n2

• Array • Space complexity 045


L
• • Unit space to store the data (Input space) and
v

Linked List exact asyrntotic


• Stack analysis analysis additional space to process the data (Auxiliary space).
• O(1), O(n), O(n2)
mmnnnvnnnn
*
unit space
• Queue *
bytes -

time
-

* *
iterations
•✓ Advanced data structures
• Tree
• Heap • Time complexity
• Graph • Unit time required to complete any algorithm.
• Approximate measure of time required to complete
any algorithm. based

some factor
on
.

Sunbeam Infotech www.sunbeaminfo.com


Time complexity

• Time complexity of a algorithm depends on number of iterations in the algorithm.

① check if mum is prime .

• Common time complexities → 0cm) : for Ci=z ; Ian ; ite)E

• O(1)→ T=k iffnl .


i ==o )

• O(n) single loop pff prime;D


. -

T&n → not
.

• O(n2)→
Tana → nested loops -

② 3

ifCi==n)
nested loops ③
• O(n3)
-

→ T×n3 →
pf f- prime ) ; "

• O(log n) →
Ta tog partitioning


n
table
'
"
point of n .

• O(n log n)→ Th tog


n n →partitioning
OC1 ) for ( i -_ I
; ic-lo.it)
repeated → :

Pf ( num ai ) ;

• Asymptotic notations → time


max -
worst case
• Big O O( ) Upper bound
-
-

min time best case


• Omega ( ) Lower bound →
-

- -

• The a ( ) Upper & Lower bound



time avg case
avg -

- -

Sunbeam Infotech www.sunbeaminfo.com


Linear Search
-

• Find a number in a list of given


numbers (random order). 88 33 66 99 44
11 77 22 55 11
foci -_a ; Ian ; ite) E
if facing ==,key) 9
index
3
setup n i .

,

return
if found
space
-
Complexity
return I found Input space : Th n
; if not
-

• Time complexity
.

ans
• Worst case → shape iterations → Th n → 0 G) Aux space K
: s =

n its
OCD

• Best case →
min iterations → T=k → b. CD1 0CD
only
mum
I itr ,

• Average case iterations



avg →
TXIZ → 0cm
)/OC
6
T h n

Sunbeam Infotech www.sunbeaminfo.com


Binary Search 40

* for sorted
array only .
0 1 2 3 4 5 6 7 8
whiles ⇐ r )

{ m= 11 22 33 44 55 66 77 88 99
( der ) 12
ifc Cm)) 9 9
key == a
n→2¥
return INT R L
2 16

'
i
log
2 =
dog n 68
p

if (
key salon))
left m
i=ds 2
-1
← past us 2
4 →

;
62
= on

Tai
else →

f- mtlj ← right part


Tate 2
dog 2
I →

} dog n
im
TX

return l
; ocdosn)
-


hmmm

Sunbeam Infotech www.sunbeaminfo.com


Recursion -
Divide & Conquer

• Function calling itself is called as • On each function call, function activation


recursive function. record or stack frame will be created on
• To write recursive function consider stack.
+8
%E④
mmmm
3!
a *

• Explain process/formula in terms of itself int fact(int n) { 4 ! 4 =

mmmm

• Decide the end/terminating condition 7


int r;
It
base
§ z④
i④
• Examples: if(n==0) '

>• n! = n * (n-1)! > 0! = 1 . I '


return 1;


xy = X * xy-1
T0n = Tn-1 + Tn-2
x0 = 1
T1 = T2 = 1
← s
r = n * fact(n-1);
-
e
&
!ON
o
mmm
=
I

• factors(n) = prime factor of n * factors(n /


^ return r; 23 2 22 =
*

prime factor) factors ( D =\ '


22 a

• Function call in recursion } = 2 2

hmmmm z
'
= z
^ 20

• Pros & Cons of recursion -

-
20 = 1
mum
res=fact(4);
mmmm

④ return addr
= - .

Sunbeam Infotech www.sunbeaminfo.com


24
Recursion > IEf= fact
<

int fact(int n) { int fact(int n) { int fact(int n) { int fact(int n) { int fact(int n) {
④ 7
③ 7 ② a
① 7 ⑥
int r; int r; int r; int r; int r;
if(n==0) X if(n==0) X if(n==0)x if(n==0) X if(n==0) ✓
return 1; return 1; ② return 1; ① return 1; return 1;
4 ③ 3 2 r o m

r = n * fact(n-1); r = n * fact(n-1); r = n * fact(n-1); r = n * fact(n-1);g r = n * fact(n-1);


r
return r; 6 return r; zr
return r; r d
return r; r
return r;
} ④ } ⑥ } ② } ① }
function activation second / stack frame FAR contains

is coated stock for fn call ① local variables


on each -

② arguments
mm

^
Created when fn called
③ return address
a
destroyed when fn return
↳ addr of next insta
to be executed when
Fn returns .

ihshru
= addr of next

after fn call .

Sunbeam Infotech www.sunbeaminfo.com


main {
Recursion Ies factor)

#
-

int fact(int n) { int fact(int n) { int fact(int n) { int fact(int n) { int fact(int n) { •

/ /
>

/
int r; int r; int r; int r; int r;
if(n==0) if(n==0) if(n==0) if(n==0) if(n==0)
return 1; return 1; return 1; return 1; return 1;
r = n * fact(n-1); r = n * fact(n-1); r = n * fact(n-1); r = n * fact(n-1);←r = n * fact(n-1);
return r; return r; return r; - return r; return r;
} } } } }
f
ff ) :n=Q,t=

ret=f C) me

ffs ) :n=¥=sm ffs ) :n=


'
'

net ,

(2) :n=2it=
f- -ret=f ff 2) ;n=zre+=f
-r=
,

ffz) :n=2it=
C)

f- C)
ff 3) :n=3it=
net
:n=3,t=
-_

f- c) ff 3)
net=f
" z
FC3) : -_nef= g
) :n=3
net -_ t
ff -3 ret=f C)
,

f( 4) :n=h,t= f( 4) :n=h,t= f( 4) :n=hit= f( 4) ;n=4,r=


f( 4) :n=h
MC7 net on t=
net -_ -_
ret=m ref=mc ) ,

net MC ) -_

res res
res M res
. -

M
-

,
. .
.

M , : M
t&%+
. . .

:
.
. .

; ,
Jvmlos net -_ JVMIOS ; ,
M
ret-s.vn/os net -_ net-s.vn/os :
jvmyog

Sunbeam Infotech www.sunbeaminfo.com


Binary Search
0 1 2 3 4 5 6 7 8


11 22 33 44 55 66 77 88 99
m -_
Cdto ) 12 ;
afm))
✓ key In my M mtl
Rm
return key
ifc actors)
key < L

bin search (d on -1
,
key)
,

" se
bin search ( anti ,
r
, key)c

base card : right C left


mmmm

4
~

Sunbeam Infotech www.sunbeaminfo.com


Sorting

• Arranging array elements in ascending or descending order.

• Popular sorting algorithms


• Selection sort

÷ ,
• Bubble sort
• Insertion sort
• Quick sort
• Merge sort
• Heap sort

Sunbeam Infotech www.sunbeaminfo.com


Selection Sort 6 4 28 3 1

For Ci=a ios ; it -1 ) {


; 0 1 2 3 4 5
forcj-itlijac.it {
if(aCN I 2 3 4 68

swapfaCD.at;D; f f
>
3 ~
G- G-Dt .tl
-
5
i=
@ + + to 5
3
.
.

D12
non
p j
i=
i= to 4
-

I -72 5
Approbation
-

n of
+ a
2
Theory
n 77 I
i=zpjTz to 5 -

3
Th
riz i=34
'
n - n
to 5 - 2

i=4#
'
Th n order terms
all lower to 5
neglected I
0-45
-

can be .

Sunbeam Infotech www.sunbeaminfo.com


Selection Sort

class Persons : id name


, age .

0 1 2 3 4 5

} I % I § I
a

For Ci=a
;
iss ;i++ ) {
forcjnitl ;ja6;jt {
iffaci ) .
age >
a
G- 3. age )
swapfaCD.at;D;
3

Sunbeam Infotech www.sunbeaminfo.com


Thank you!
Nilesh Ghule <[email protected]>

Sunbeam Infotech www.sunbeaminfo.com


Data Structure & Algorithms
Sunbeam Infotech

Sunbeam Infotech www.sunbeaminfo.com


Bubble Sort 6 4 28 3 I

ite) {
ian i
;
forcing
-

0 1 2 3 4 5
fooCj=o ; jam -
I;jtt) {
D) I 2 3 4 6 8
iffacj ) > a

D) I
4 9 swap ( ACD
a

innermost
,

)
j jtl i=o : 5 its

} Daca D
i=i : 5 its
i=Cn ④
-
-

§→
is : sites
T N2-2MT I
4 i =3 : 5 its

i=4 : sites
T4
'
n
-

@ -
1) camp

Sunbeam Infotech www.sunbeaminfo.com


Bubble Sort -
improved Bubble Sort

ite) {
ich i
;
foCi=o ;
-

0 1 2 3 4 5
ijjtt) {
fooCj=o;jcm -
I -

ifCacFFaCjtD ) 2 3 I 4 6 8
D) -

swapcacjs
f f
a
,

inner
3
loop
3 i-k-D-cm-DT.e.tl -

ix. : 5
'
Th m n
i. I• :
4
+150
-

i=2
.

:3
i=z : 2
-1=4 : I

Sunbeam Infotech www.sunbeaminfo.com


Bubble Sort -
more improved Bubble Sort

is n i
;
it e) {
forcing
-

0 1 2 3 4 5
Flag false
Swap
=
;
{ 2 4 6 8
for a
;jcm -
I -
ijjtt) I 3

ifCaEjTFa D) E

( a CD a
D) -
f f
swap ,

swap tone :
flag -_

Best cage :
array already
g mmmm sorted .

If wap Flag == false) a


inner loop is executed only
break ; once .

i= n I
3
-

Th n - I
0④
Sunbeam Infotech www.sunbeaminfo.com
Insertion Sort 642831

68 2
I 3 4
0 1 2 3 4 5
~
I 2
a
3 46 8
④ 283 I

9 i=i

-1=2 246
- i=2

S
2468
-1¥ I 2 3 4 i=3

'
23 4 68 23468
^
i=4
8
9 I 234 6
I i=5

9
Sunbeam Infotech www.sunbeaminfo.com
Insertion Sort
is Itzt . .
-
+ G-D
is non D12 - 0 1 2 3 4 5

6 4 28 3 I

7LM 2- m
1 4 6

2
I
⑤ +3 276 ?⑤
4
2%6 ?①
F34 6EO
5 r -

Sunbeam Infotech www.sunbeaminfo.com


Insertion Sort

0 1 2 3 4 5

I 23 4 68

/
Tan
BEI OCD

Sunbeam Infotech www.sunbeaminfo.com


Linked List REFEREES
at runtime
• Linked List is list of items linked together. → can grow / shrink .

sequential access only


• Each item in linked list is called as Node.
.


mmm

overheads
• Each node contains data and →

alloc
mmm

pointer/reference
F
to the-
next node. →
not contiguous
.

• Linked list is linear data structure.

Arrays • Linked list ADT


-

OCD
• addFirst() ✓

① random access →

• addLast() ✓

② fixed size
Ishoink of runtime .
• addAtPos() ✓
cannot grow

-

deleteFirst() ✓

③ contiguous allocation
• deleteLast() ,

overheads • deleteAsPos()
④ no
required

extra space
no
• deleteAll()
-


data elements
other than .

• traverse C) or display C)

Sunbeam Infotech www.sunbeaminfo.com


Linked List
head

• There four types of linked list.


-
③ mode mode mode

• Singly linear linked list - >


d
11
n

20-0
d
223-00
n
d
33
n

q
• Singly circular linked list LEE IE9 3IM
• Doubly linear linked list
-
head

\
-

100

• Doubly circular linked list

\
11 200 22 300 33 I

1002003007ft
y

Class My
list
{
static member
Hoda head ; class head
data { >
d n d n p d n
p
class Mode {
I ' '
20-0 E0223Y 33 I
,
display C)

{
data ,

ops{
type
ad ELI
date
mode next ;
nea '¥ ¥ son

100

{
=
0ps
¥rf
ioa✓
>
300 33
=
22300¥00
11 200 100 100
, ,
-

3; 3 z

Sunbeam Infotech www.sunbeaminfo.com


Linked List -

display

head head tear = head ;





④ 350 ⑤ %

q÷÷i
-

, →•

*
-

train =
trav.net ;

Sunbeam Infotech www.sunbeaminfo.com


Linked List -

add Last C)

head not
100
L
11 200 22300 33 4×57
mum
441 @

IO0 2OQ 300 ↳ QQ


inn

4tour
-
& init it

sina.IE?jde./DFi?wnikfhI iI n'
nude list
empty ifinead - uD
.

① create new

Mode nn= new Mode my


head -_nn ,

② in
:[
node into next of last node

③ add new .
goo
next
-

train . = nm ;

Sunbeam Infotech www.sunbeaminfo.com


Linked List -
add Firste )
nm

③ head

Fido
44
If QQ 11 200 22 300 33 0

↳ QQ IO0 2OQ 300

ahlocdinitnewnodemoden -neIII.
wtlodelraDi@nenwn .gh

¥0
emnnndeaad

node
③ head should be new .

400
head

Sunbeam Infotech www.sunbeaminfo.com


add Atposc ) before
Linked List -
make break

spd :3 odd node beyond pos .

9
head
100
2 3
5
I

11 200 22 300 33
④0 X 7 44 0


¥aIH#④$
' oo z oo ggg 900

g
Stand:[I
↳ ¥
.

I 05¥
③ nn
Sunbeam Infotech www.sunbeaminfo.com
Linked List

HI;D
,
} 3

iqa
" " "°

¥°z ,
33 0

need

↳ 11 → 22 → 33
µT*a
→ 44 → ST
]
9 f
temp tour

Sunbeam Infotech www.sunbeaminfo.com


Thank you!
Nilesh Ghule <[email protected]>

Sunbeam Infotech www.sunbeaminfo.com


Data Structure & Algorithms
Sunbeam Infotech

Sunbeam Infotech www.sunbeaminfo.com


Linked List List
-

Singly
head
① display :
OCOD

② add Last : 0cm) to → 20 → 30 →


403
③ add First : OCD

⑨ add At Pos : 0 (pos)


avg.io
⑤ del First : OCD

⑥ del Last : OCD

⑦ del Athos : )
Ofpos
avg : Ocr)
⑧ detail :O

Sunbeam Infotech www.sunbeaminfo.com


Linked List List
-

Singly
head tail
① display :
OG3
%→za→3•
µ

② addlast : OCD →
403
www.mmn

③ add First : OCD


tail nm
head
⑨ add Athos : OCPOD a>
a
&
avg 0 I @ → z@ → → → 40
-9503
⑤ del First : OCD tail next am
. -_
;
del OG3V tail
⑥ Last :
-_ mm
;

Y%
del Athos OCPOSJ head tail
⑦ :


airs : %)
%→2a→3o→aoz
detail ←
f¥g
.

:O

Sunbeam Infotech www.sunbeaminfo.com
Linked List -

Singly Circular list .

head
100

+ rare heed ;
' ' 200 22 300 33 I @

'§←a3oa✓→
do {
pf( tour . data) ;

trav-toav.me xti

while ( trev !
- ↳
3
-

22 33
11

¥ if list is empty ,
return :

Sunbeam Infotech www.sunbeaminfo.com


Linked List -
add Last C)

head
frau
t t
To →$④ 4



so
.

to → see → →

am

F%
special : ③
① create non & init tisn
I 0

last node CH Io?.de


W→
till
② traverse
should be

had
③ msn.net
III
=

④ toav .

next = 'M
mn . next = head
;

Sunbeam Infotech www.sunbeaminfo.com


Linked List -

add First c)

① create nn & init


① nn head ②

f f
.③-
t
20 30 →
t
40
② train till last node

¥✓
to → →
go ③ nn near = had

④ last nude nest -7

③ head =
may

Sunbeam Infotech www.sunbeaminfo.com


Linked List → add At Pos .


damn

µ #Tf③
head

! a a → to

£N\pos÷|
1 → so → 30 *

i =3 pos = 8

§→aa→oyHoIµ
head

Sunbeam Infotech www.sunbeaminfo.com


del First C)
Linked List →

empty
⑨ if list is
head
ftp.w
,

exception
&§O
throw
¢
.

10 → → 30 → 40

n§jfW §d]÷n:±Eu
see

5l
① tour till last node .

87:*:[ 5%9

Sunbeam Infotech www.sunbeaminfo.com


Linked List → del At Pos C)

"

Id→
÷W
so
• →

Sunbeam Infotech www.sunbeaminfo.com


Linked List

feed 3②
1£ to



→ to → so

list into singly tin list



.

convert air

head next
-
=
null ;

② make had null


head ± null ;

Sunbeam Infotech www.sunbeaminfo.com


Linked List -

Doubly Linear List


head
head


L
65%7207303
10 2007 300-20030 Q

\gi
a 20

[ so . yg
of next node
next → adds
node
poor

adds of poor
.

Sunbeam Infotech www.sunbeaminfo.com


Linked List - display C)

head head

!
1 ✓ r
r ✓ ✓ it

T > 20730740 ]
{0520730--40} g.
tour head ; till last node
=
① traverse
null )
.

while Ctrav ! =
tour heads
=nW)
{ data
)j while Ctoav next !
pf ( tou
.

next ;
next tour
train din
.

tour tour
ten
in
.

z each node
② train & point
null )
Ctrov f-
forward display while
- 9 point ( ther data).

trait trav .
poev ;

ooorqdispby_
Sunbeam Infotech www.sunbeaminfo.com
Linked List -
add last c) ladd First C)
not
trov
head

IF2A Isa > 4%3--56


.

④ head

I> • ← 30=403

⇐Eii3
node is first node .

In
Sunbeam Infotech www.sunbeaminfo.com
Linked List
sin vd=5O nn
pos=4 d ③
head ⑤
50¥
I !=aaFga=f ]
[ ①tr*v

temp

add after last pos


special
.

case ; hnvd=sz tin

g-
t
pos =

mff.SI ]
head

& - zo
- go → Leo
Eve
]
- - ←

p 4
[ tear
temp

Sunbeam Infotech www.sunbeaminfo.com


Linked List -
del first C)

[IIEa > so I 403


¥4.gs Too

Sunbeam Infotech www.sunbeaminfo.com


Linked List - del last

head
trav

It The
[
→ we
-→µe-→4a ]
traverse till P0S

.

to tour 's neat ,


node's next
② previous
to tear 's poor
rude
③ next node 's poor
-

head tmv

← ! ②⇐¥÷ 9
pipe
~

Sunbeam Infotech www.sunbeaminfo.com


Thank you!
Nilesh Ghule <[email protected]>

Sunbeam Infotech www.sunbeaminfo.com


Data Structure & Algorithms
Sunbeam Infotech

Sunbeam Infotech www.sunbeaminfo.com


Linked List Circular List add last
Dowdy
-

( head prev)
.


LED tail now

!
to
¥0 ②

I
4%0

1 → zoo → so

① tail = head poor ;


-

¥÷i¥
② nm . next = head ;

③ mm .
per = tail !

WW
a

81:
a
go

had = nm :

nm .

next = head
;
mm .
heed
poor =
;

Sunbeam Infotech www.sunbeaminfo.com


Linked List Circular List add First
Dowdy
-

hmx.ch?OdtaiJmTDnnmTGO
→④&
%
x d

#
4%0

→ za - so

① tail = head poor ;


-

¥÷i¥
② nm . next = head ;

③ mm .
per = tail !

WW
a

87:
a
go

⑥ head = mm ; had = nm :

mm .

next = head
;
mm .
heed
poor =
;

Sunbeam Infotech www.sunbeaminfo.com


Linked List Gt List
Doubly
-

head tnv
L t

1a→←2a→3oI4JW
find display our display
-
-
tonne heed
;
tonne head prev ;
do f
-

pfctrav.dk)y dog
ttrav-tonu.net ; pf ( traviata);
tractor poev ;
);
.

rsahikctow ! heed
gwwectnwl-heed.ms;
-

Sunbeam Infotech www.sunbeaminfo.com


Linked List
DowdyCirt Linuxke.me/- circular list
all lists are doubly .

Time complexities
-

table
mmmm
① job queue / process

/
① add first -
OCD

② add last - OCD ② ready queue

③ del first -

OCD ③ waiting queue

del last -
0 G)
④ ④

[email protected]
0cm)
?
⑤ inode tab

① G ofn)
linear search

Sunbeam Infotech www.sunbeaminfo.com


Linked List Competitive programming
• Sort the singly linked list.

head

I
I
5 → 6 → 4 → 3 →
]

selections ✓

i.me#t!=null
Mode isj ; murmur
i ! null ;
iii. next ) {
for ( i heed ;
7 E
=
✓ -

j ! - all I t-j.net
for = i. next ;

5. data
)
if ( i. data 7

swap ( i. data );
5. data
,

3
I

Sunbeam Infotech www.sunbeaminfo.com


Linked List Competitive programming
• Reverse singly linked list.

old head oldheed -_ head


;
I head = null
;

while head ! and


-

-[tmP=
oldheedjoldhead-oldheed.net
aaaa.sn#II:IE;edi
del first
-9
;

head
t s
→ see
1oz

a →30

A
temp

Sunbeam Infotech www.sunbeaminfo.com


Linked List Competitive programming
• Reverse singly linked list.

old head

head

4% → 30 → be → to
]
1
temp

Sunbeam Infotech www.sunbeaminfo.com


Linked List Competitive programming
• Reverse singly linked list using recursion.
){
h
h
Mode oecRev(Mode
⑤ aa→3a] ifch.net
-_=nW){

[a→o→aa↳ in
] ,
IE47
t-sec.Revlh.net) ;
;

④ so → we

]
t.net -_ h
;

aa→z&w
-

{④÷
h next nun
;
- -_

} Hmm hi ,
s
,

④ hey

301
Sunbeam Infotech www.sunbeaminfo.com
Linked List Competitive programming
h

• Reversetsingly linked list using recursion. mark it


⑨ if dish has sioglenode , as
to → see → so →
403 head & it ( it is last body

£9
return

-

to
① reverse rest of list ( from )
next
[4+0]
after last model's
② add our node CD

I. →

71: : I :3 :I→ .

§↳;
④ "" our nodeoasrn.us ;
>

f÷ If
he
?
Sunbeam Infotech www.sunbeaminfo.com
Linked List Competitive programming
• Reverse singly linked list using recursion. Node oecRev( Mode )fh
head
h t itch next null )q

/
.

6 I head =
hi
return h ,
to
# 30
# 403

]fjW
see
z

±:i÷÷n;cnne
,

G. next - multi
return h
;
}

"

¥5 "

¥44
recRevCasoFh¥To5;h
Sunbeam Infotech www.sunbeaminfo.com
Linked List Competitive programming
• Reverse singly linked list using recursion.
in order
Display singly list

]
reverse
.

our Display ( h) {
head

L → if list is empty , return ;

Ice
403
→ see → 3 a →

list ( after ninety

#
of
it →
display rest ;

node

2¥ display
→ cur ;

3¥ ] 3


h


mm

%±¥ h

Sunbeam Infotech www.sunbeaminfo.com


Linked List Competitive programming
• Find middle of singly linear linked list. h ×

head % → see → z @ → he
→ to → Go → 70s to

I x
9
Ice so → 40 see
]
- see → -

even
nodes
offers
taste heady £
approach I slow had
,
/ &&
.net?=nulD3whIleCfaot!=null
=

at nodes fast
① traverse list & count mum .

② traverse till Count 12 . slow =


slow .

neat ;
'

fast = fast .
meet - next ,
2
approach
fast & slow
1¥ two pointers -
.

fast Fastnet meet ; data → returns


② traverse fast pointer : =
.

slow .

slow pointer slow slow next


;
.

:

=
traverse

Sunbeam Infotech www.sunbeaminfo.com


Stack and Queue

• Stack & Queue are utility data • Simple queue is First-In-First-Out


structures. temp# wring

process structure.
.

• Can be implemented using array or • Queue operations ADT -

-
linked lists. • push() league 's
-mmmmmn

a 9g In 9g In
• Usually time complexity of stack & • pop() Ideauec )
queue operations is O(1).
if• peek() I f
✓ • isEmpty()
• Stack is Last-In-First-Out structure. • isFull()*0
front rear

• Stack operations ADI


• Queue types

€ %÷④

✓ push() • Linear queue
• pop() • Circular queue
:• peek() • Deque

• isEmpty() • Priority queue
0
• isFull()*

Sunbeam Infotech www.sunbeaminfo.com


Stack / Queue using Linked List

• Stack can be implemented using LIFO

linked list. FILO head


6
}r
✓• add first → push → OCD

¥# * →*
um

✓• delete first → pop


mm
→ OCD
add oc→
• is empty → isfrnpty C)


✓ →
OCD in

head data OCD


%→ - → so→④→ded→oc→

peek → return •
;

4 LIFO ← not

test
hmm efficient
shyly
• Queue can be implemented using with
with head & toil

linked list. singly distanced

✓ • add last → push C) uokfh.de#T OLD


FIFO
mm
OED
✓• delete first → Pope 's OCD
LILO
( )
-
i

✓• is empty → is
Emptying OCD
✓ peek data OCD OCD

seen , head .
;

Sunbeam Infotech www.sunbeaminfo.com


Stack -
using array

push :
init :

5
top -iY top= -1 ;
aorctopj-v.at ; arr -
new intl ]
;
*

4
peek : ←

* *

3
acheron arrctop)

ppp 34¥01

2
:

top - -

i

1
is Full :

top==
I *

0
man -

aor
is Empty : -1
top →
I
top== -

Sunbeam Infotech www.sunbeaminfo.com


Stack / Queue in Java collections

• class java.util.Stack<E>
mmmm
• interface java.util.Queue<E>
mmmm

✓• E push(E); ✓• boolean offer(E e); -


push
✓• E pop(); ✓• E poll();-
pop

-• E peek(); -• E peek();

• boolean isEmpty(); .• boolean isEmpty();

r
Array Deque
Linked List ✓

Sunbeam Infotech www.sunbeaminfo.com


Expression notations .

⑥ ① ⑤ ② ① ⑧ ④ ③
infix A + B a human fmath

5+9 4^(8-621) -11$ (7-3)

}
potefix
-

computation expression
-

+ A B
$0 3)
-4^8621--1-1
-

, algorithms notations 5+9

pos¥× trashiness 5-19-4


+1,413¥
a
A Bt

5+9-4 a
862-1--1 -

infix result ✓
$
4862 +
→ 173 -

5- + 9- -

uggz +173-1
result
infix → post fix →
5¥ -

+173-459+4862
result
infix → prefix →
5g+↳862
$ +
/ 173 -

- d-

precedency -

( ) highest ⑧ ④

}

⑥ ⑦ ⑤ ② ① ③

$

*
% ¥¥81$I-
1- - ← lowest

Sunbeam Infotech www.sunbeaminfo.com


operands
Postfix Evaluation Stade

• 59+4862/-*-173-$+ +

post fix from left to right



.

traverse

stack
if is operand push on
.

② syon ,

two args
if is operator pop
③ Sym ,

calc result & push on stack


From stack
.

/ second roped
1st op
2nd
-
.

first piped op
-

done
④ repeat z & 3 until all values from expo are .

⑤ pop the final result from stack .


-5

Sunbeam Infotech www.sunbeaminfo.com


Thank you!
Nilesh Ghule <[email protected]>

Sunbeam Infotech www.sunbeaminfo.com


Data Structure & Algorithms
Sunbeam Infotech

Sunbeam Infotech www.sunbeaminfo.com


Stack and Queue

• Stack & Queue are utility data • Simple queue is First-In-First-Out


structures. temp# wring

process structure.
.

• Can be implemented using array or • Queue operations ADT -

-
linked lists. • push() league 's
-mmmmmn

a 9g In 9g In
• Usually time complexity of stack & • pop() Ideauec )
queue operations is O(1).
if• peek() I f
✓ • isEmpty()
• Stack is Last-In-First-Out structure. • isFull()*0
front rear

• Stack operations ADI


• Queue types

€ %÷④

✓ push() • Linear queue
• pop() • Circular queue
:• peek() • Deque

• isEmpty() • Priority queue
0
• isFull()*

Sunbeam Infotech www.sunbeaminfo.com


push → rear
Linear Queue pop ← front
7-
gigs
init :
-


into - is Full :
-
p 0 1 2 3 4 5
a- = new ,
t MAX I
f- -1 ; -


304050 60
=
v

+ -1
=
; is Empty : 7

/
- or
push : &
f==r
rat 's
val
array -_
;
improper memory
:
-
pop utilization
r=CrxD%m
Fttj
I a
ifCr==mAx -
)
i
I
-
- → I
see
'

peek : Y }
r=a
;
-
I

-
5 else no

I

return anrfftl ) ; 2 r=o+i ; I → z


q
a
L r
r 33 ?
G-
3 4 → 5
5ns

Sunbeam Infotech www.sunbeaminfo.com


Circular Queue

• In linear queue (using array) when 0 1 2 3 4 5


rear reaches last index, further
elements cannot be added, even If
space is available due to deletion of
elements from front. Thus space
utilization is poor.
• Circular queue allows adding
elements at the start of array if rear 1 2
reaches last index and space is free at
the start of the array.
• Thus rear and front can be
incremented in circular fashion i.e. 0,
[
0
1, 2, 3, , -1. So they are said to be 3
circular queue.
• However queue full and empty
conditions become tricky. 5 4

Sunbeam Infotech www.sunbeaminfo.com


Circular Queue -

full 4 push
-_
hmm

-1 0 1 2 3 4 5

OR Go to 60
' a
20 304050 6g go 809A

f- 5
f- •

r==max It (f==1 - old f ! =


-

1)
&&
(f== I 2
-

pushed
0
• =(rtD% Max ; 3

arr =vd ;

5 4

Sunbeam Infotech www.sunbeaminfo.com


Circular Queue -

empty & pop

Wtf
"
0 1 2 3 4 5

* * 38¥

"

Tiff
I=¢
{
f==
, max ,

0
1 2

3
5 4

Sunbeam Infotech www.sunbeaminfo.com


DeQueue
hmmmm

• In double ended queue, values can be added or deleted from front end or rear end.
=
=
t
'

applications of ,] OCD
-

push back
RTOS
-

message queue
in .

push -
front
back
pop
front pop -

Normal
-

urgent Ofc)
0
or OCD head tail

1 I
0--0--0=0
in 4 11 22 33
head tail

Sunbeam Infotech www.sunbeaminfo.com


Priority queue → Not a FIFO
queue

• In priority queue, element with highest priority is removed first.


↳ internally elements are stored in sorted manner .

CambeimpIemen 5 9 6 2

① using array → insertion logic . fmnnmnn


insertion dosic head
using clinked list
.


② 1
III = 0cm) 2 →
5→6 →
9
×
pop = 0 ( i)
mm

bin tree)
✓③ using heap ( array representation of .

efficient push •
flog = ) ~

• Clog n)
mmmm
pop =

Sunbeam Infotech www.sunbeaminfo.com


Stack / Queue in Java collections

• class java.util.Stack<E>
mmmm
• interface java.util.Queue<E>
mmmm

✓• E push(E); ✓• boolean offer(E e); -


push
✓• E pop(); ✓• E poll();-
pop

-• E peek(); -• E peek();

• boolean isEmpty(); .• boolean isEmpty();

v
Array Deque
Linked List -

priority Queued
hmmmm

Sunbeam Infotech www.sunbeaminfo.com


Infix to Postfix

• 5+9 4*(8 6/2)+1$(7 3)

① traverse infix from left to right .

if operand found appeal to post fix .

② ,

to stack ⑨
③ if operator found push
,

stack >
priority
=

② if of topmost operator on
it from
priority of current operator pop ,

stack & append to post tix .

④ if
opening C found push it on stock .

,
&
⑤ if
closing ) found pop operators from stack
,

is found
append to post f. × until opening .

also
pop & discard opening C from stack .

⑥ if all
syrms From infix are completed pop
one by
,

one & append to post fix .

Sunbeam Infotech www.sunbeaminfo.com


Infix to Prefix stack

• 5+9 4*(8 6/2)+1$(7 3)

Sunbeam Infotech www.sunbeaminfo.com


Prefix Evaluation stack

• +-+59*4 8/62$1 73
1

✓ ⑤
Sunbeam Infotech www.sunbeaminfo.com
Parenthesis Balancing @
I 2

• 5+([9 4]*(8 {6/2})) × open C [ {


9 close
) ] 3

a o

I 1

( )

8
+
Sunbeam Infotech www.sunbeaminfo.com
Stack / Queue Competitive Programming
• Reverse array, string or linked list.
-

)
/oc→
it +
isnt
for Ciao ,

push Carr CIDI


(=p) =gfg?
g.

fan
it )
-

for Ciao ; Ian ; )


aorc D= s -

pop D; -

Sunbeam Infotech www.sunbeaminfo.com


Stack / Queue Competitive Programming
• Create two stacks in single array in efficient manner.
• I 2 3 9 5 6 7 ⑧ ⑨ to 11 Init 2 :

init

1/2/3/4 15/6/71 8/9/-30/40


:

topz=arr_ death
topk -1

f p
is Empty ! :
is Ensign :
→ ←
topz-e-anr.leh.sn ;
topI== -1
top )
top
push 't ) : pvehs.CI :

tops
-

I
topher,
-

✓topI+I==top2 a- CtopD=vd;
a- CtopD=vd ;
:
C) : wtopl ==topz I Pops
pop )
-

topzt -1

topl topz top I = =)


j ✓
- -
-

is Full :
is Full :
topHI==topz
top.lt/=EtoP2
Sunbeam Infotech www.sunbeaminfo.com
Stack / Queue Competitive Programming
• Create stack using queue. fq ~

LIFO F£Fo
-50 →
the 40 30 2@ to

f r


push → OC5

t④ik( t.q.is Empty E te


tq push
.

( 9. pop D) j
3
pop ' → OLD
=

g. push Cual) ;
g. pop
while (Itq . isEmpty 3) {
q' bush ( tq Pop (3) I
.

Sunbeam Infotech www.sunbeaminfo.com


Stack / Queue Competitive Programming
• Create queue using stack.

Sunbeam Infotech www.sunbeaminfo.com


Thank you!
Nilesh Ghule <[email protected]>

Sunbeam Infotech www.sunbeaminfo.com


Data Structure & Algorithms
Sunbeam Infotech

Sunbeam Infotech www.sunbeaminfo.com


Hash Table -

Searching

Hash Table is Ds in which data is stored in key -


value
Searching
pair value
,
so that for
-
,
a given key can be searched
① Linear → 0cm)
in fastest possible time Ideal is OCD
ocdogn)
.

② Binary
.

-

Ds
value pair associative
key -

+ ③ Fibonacci
name
mobile
e. is Mobile Contacts appIn
→ OLD

(value) ④ Hashing
.

( key)

ideal
mmm
Hash ADT
mmmm

① put ( key ,
value)

② value = get CKED

Sunbeam Infotech www.sunbeaminfo.com


in alumni meet man laced students will come
students with
an
A class have 50 roll 1 to 50 . .

invitations sent to 5000 students .


store details
store students so that student Can be found that student be
, so
given prn mum
,
can

in fastest way for given roll found quickly 3 ✓

collision
.
.

Student [503
table - ( key) y
a

-
L 7 102 t

'

find
2001 = open chaining
addressing
5 ✓
roll no 2

£2
-
z@ @
230oz = -
-
mm =

I
arr [ 5- I3 0CD 33T t
4998

fm
-
3 mm
rehash to
_< If 4 find possible 2001 ✓

3 '

slot 2

}4
- 5 L .
- .
z I @

Jfk )=(slot -113%1000


Abc hmm
run a : -

Oct) 77 ! -3 162
slots slot
-

→ .
f( key) =
neo
- mm

aoe¥m
"

{
§
-
two diff keys
7 key
• -

I
/
= lol 3102
-

in same
! -
-

1oz ,=&z ,@z


resulting

0IIim£sn,
: -

hasnfn ⇐¥=e
-

-
ag G :
31¥ lead to collision
48
'
- .

( par
-
55 i

-
i
49 c
h(k)=K% head
)
.

9984998T
Reign rake 999
-

£999
Sunbeam Infotech www.sunbeaminfo.com
openaddress.in# Load factor
call rehash Fn -

① if collisions occur
of kv pairs
.

,
num
slot -
② rehash fn find next possible hymn of slots
to store / find the element → probing
of slots

;%aIF"÷
③ rehash fn a
hum of KV pairs < mum

b
↳ linear -
are +
load factor < I

{%
a

• slots
a
mum , kv pairs = mum

a load factor I

=
find process :

slot of slots
⑨ hash an →
the slot
A
hum of Kv pairs > mum

if He found in .

③ check

↳ ② if

raped
not call

b&c
rehash

until
fn
de
.

is found .
( a

open
load factor

addressing
7 I

cannot be used .

is internal
mechanism
⑤ open addr

storage .
Data stored within array table .

Sunbeam Infotech www.sunbeaminfo.com


chaining
hmmm
Java collections : Hash Mars ,
- .
.

3 -

GOOD
-

chaining method
whiff arr
iaz
-

t.TT#-

zaozv hCK)=¥7
✓ is the
4998 ① the nuns of collisions slower
TE3
-
more ,
2 →
&
.

- 2001 ✓ performance for add search

→⑤=
.

② (uniform) hash fn

2102 ✓ to seduce collisions better


4 a- umm
should implemented
be

31th
" .

prime non
③ it is observed that multiply by
-

'


163 ✓
'
-

makes more uniform hash fn .

: external
-
e. s .
hC key) =
fkeya 3D 's .
slots .

storage
height
100
bucket

e. s shore students as per


their

.
-

101
& feetl inches
. →TE±dT

& & height value student .

key
=
- = ,

he % slots
'
TAE hckey) = az ) + inches

31 ) ;
'
-
find 192 slot
qq.SI/J998=--- Gseareh in
° 3102
999 mm
bucket .

Sunbeam Infotech www.sunbeaminfo.com


obeys
teethed
taste

a _-① 39 T.io =¥
\
Ryan
_→⑨→n
2
_→①


I
6
I8⑦I¥EEi⑤p
→I¥ g
oesranuim
b- t.io -_o



7 ¥ 28%10=8

.→i
×

Diana
9 →

Sunbeam Infotech www.sunbeaminfo.com
Tree Definition

• Tree a f e e f de h e ec a de g a ed de ca ed he root a d
the remaining node are partitioned into disjoints sets T1 to Tn, where each of those
sets is a TREE.
• T1 to Tn are called sub-trees of the root

%⑧ "

.
D= -

o÷%¥÷ *
Sunbeam Infotech www.sunbeaminfo.com
Tree terminologies
data pointers
• Node: A item storing information and branches to other nodes
• Null Tree: Tree with no node (empty trees
• Leaf Node: Terminal node of a tree & does not have any node connected to it
• Degree of a Node: No of sub trees of a node
• Degree of a tree: Degree of a tree is maximum degree of a node in the tree

Sunbeam Infotech www.sunbeaminfo.com


Tree terminologies

• Parent Node: node having other nodes connected to it


• Siblings: Children of the same parents → op on
,
BCD MA
,
'

PG

o
Descendants: all those node which are reachable from that node →

um

• Ancestor: all the node along the path from the root to that node C → HMM

@
not →
④ M → H C A

⑧ ¥④¥
, ,

→ a → J
,
D. A

#
%

Sunbeam Infotech www.sunbeaminfo.com


Tree terminologies → gantroveosial
3

• Level of a Node: • →
④ a

§
-
2
• Indicates the position of the node in the hierarchy ← a
a →
• Level of any node is level of its parent +1
• Level of root is 1
• Depth of a node:
-

'¥o¥z
a
• Number of nodes from the root to the node.
• Depth of root is 0
• Level = Depth + 1
• → Ako '⑨←a.

• Height of a node:
• Number of nodes from the node to its deepest leaf.
• Height of node = height of its child + 1 ⑦ a

• Height of empty/null tree is -1


• Height of a tree: Height of root of the tree.
II
"

• Traversal: Visiting each node of tree exactly once

Sunbeam Infotech www.sunbeaminfo.com


Types of trees

• Binary Trees → man 2 child nods for each mode .

• It is a finite set of nodes partitioned into three sub sets:- Root, Left sub tree, Right sub tree
• Binary Search tree
• A binary search tree is a binary tree in which the nodes are arranged according to their values.
left child smaller than mode

multi way tree right child greater than nude .

#
or end
or
n free / \ class Mode E
way
.
-

B
teach C int data ;
node have multiple child nodes Mode left ,
.

yy y ×
class Mode {
Mode right ,
p E F
data ;
-

int
/
-

xx X \
Listciuode> children ; / G
3
-
I H
=
>
Binary tree

Sunbeam Infotech www.sunbeaminfo.com


BST

E In , 2mi I ' In II. hi ?m In ,

/ \
8
z

1 I 1 ↳
6
I
91
4
I
3 6

Sunbeam Infotech www.sunbeaminfo.com


BST 5g , 3g ,
¥ , I9 1OI , log ,
I ,
89
,
Go
,

: " .

:# 0¥ I
0¥ ¥40
Sunbeam Infotech www.sunbeaminfo.com
Binary Tree Traversal
P
• In-order: L P R
/
- - m -

• Pre-Order: P L R I
mm
mm - -
L
R
• Post-Order: L R P
mm -
-
in

• The traversal algorithms can be implemented easily using recursion.


• Non-recursive algorithms for implementing traversal needs stack to store node
pointers.

preorder ( toy) .

if C tra r = = null)

return
;
print ( too v. data) ;r

preorder ( tra v. left); ✓

preorder ( tour right; . r

Sunbeam Infotech www.sunbeaminfo.com


BST → preorder -
recursive .

:÷÷÷D
:*
I
50

"

30 90 → point (traviata) ;

10 40 70 100

50 . . .

20 60
§④
80 . 70 Go so
lace

Sunbeam Infotech www.sunbeaminfo.com


Assign g
mmmm

I t t t
4 h t h b a

*F*±!÷F%×××"*
PI

Q 2 3 6 4? she

P2 P3 P4 P5
.pl
class Job {
waiting turn-around vid ;
PI a -
a = a 14-0=14 ✓ arrival
,
P2 14-2 =
12 see -2=18 ✓ burst;

P3 2CE -3=17 30-3=27 ? waiting;


P4 36-6 32-6=26 ? turn aroun
=
24
P5 40-90=0 50-46=10
z

Queued Job > . . .


Thank you!
Nilesh Ghule <[email protected]>

Sunbeam Infotech www.sunbeaminfo.com


Data Structure & Algorithms
Sunbeam Infotech

Sunbeam Infotech www.sunbeaminfo.com


BST -

height C)

.③
50

30 90

10 40 70 100

: 20 60 80

Sunbeam Infotech www.sunbeaminfo.com


BST
-

preorder

studs
50 out
tour
-

= -
;
whikctoav !=nud It !s.IsErpb {

/
30 -
90
- wnilectrav !=nulDE
printctrav.dk) ;
ifctoav right !=nuM)
40 70 100
-

10 is"
iii.
-
-
-

,
20 60 80
iffl.s.is Empty ) )
- - -

tour -_ 5. poplj
50 30 I @ zoo 4g ;
g
90 70 60 80 IQ0

Sunbeam Infotech www.sunbeaminfo.com


BST -
inoder

50 toav=root ;

whileftoavl.nu///!s.isEropgs
-

30
-
-
90 whilectoav ! -
null ) E
S -

push Ctoav)
10 40
-
70
-
100
-
tour - train left ;
.

& 3

ifcl.s.is Empty {
20
-
60
-
80
-

toav-s.p.pl ) :

print granddad ;
10 20 30 40 50 trav-trav.rs'ght;
I
60 90
70 80 too 3
Sunbeam Infotech www.sunbeaminfo.com
BST -

Bts -

Breadth First search -


Level wise search
-
Non Rea
hmmm

50 50 30 9@ IQ40 0GD
70 160 20 60 80

g. push Goot) :
30 90 ) {
while C ! g.
is Empty

→ train q pop C)
.

train )
data
40 70 100 if ( key
.
==

10 return tour
;

d- ifftrav .
left != null)
left)
20 60 80 g. push ( train .

;
if
m

I
right !→ulD
tear .

q
= 2 .

push ( traurightj;
}

return null ;

Sunbeam Infotech www.sunbeaminfo.com


Dfs Depth First
BST search -0cm)
-
-

50 50 30 10 20 4@ 90 7Q 60

80
5. push trout) ;
30 90

whilecfs.is#rnptycD9Eoav=s.popDj
tour data)
10 40 70 100 →
ifckey == .

salmon tray
it is ( tar .
right !=awd)
20 60 80
im

s.pwshftoav.oishtjifftrav.ws/.=nuhD
s -
push (tour left) ;
.

g
100 return imull ;

Sunbeam Infotech www.sunbeaminfo.com


BST Binary search 0C height
-
-

50 65
win
trar=ooot ;

while Ctrav ! - ME
30 90 if ( key == toav data)
-

northern train ;

ifckey straw - data)


10 40 70 100
traktor . left ;
else
took too v. right,
20 60 80
3
it return mall
;

Sunbeam Infotech www.sunbeaminfo.com


BST Binary search 0C height
-
-

parent null
=
;
50 tear =
soot ,

while Ctoav ! ME
30 90 too v. data)
if ( key = =

northern {trav ,
parent 3 ;
&
40 70 100 Parent = tear
;
10 if C straw data)
key
.

tram = tour . left ;


it
20 60 80 else
train =
too v. nighty
3

return {mall nutty ,


;

Sunbeam Infotech www.sunbeaminfo.com


BST Delete Node → train -
left ==nuU

p p ifCtrav=- root)
50 10 toot =
traviright ;

¥×f

⑤x§
"

30 90 20 30
:3
to30

else
P.right= tour .

right
40 . 40 40

Sunbeam Infotech www.sunbeaminfo.com


BST Delete Node toav .

right == null

if f tsar = = sooty

p p roof trav left


;
.
=

50 100 s

:*
¥ ④% 5¥
30 90 90 110 90
p .
night - tear .
left
;

⇐ 70 70 70

Sunbeam Infotech www.sunbeaminfo.com


BST Delete Node → thar - left ! all && tarnish I. =
null

60
50
=
^
parent tsar
=
;
since = trav -
right ;
30 90 whileCsucc left
-
-
I. = null )E
parent = succ
,
succ = succ -
left ;
P
10 40 70 100
3
data ;
€E t.rav.data-s.ua -

35 60 80 trove since
→ ;
④ y
65

parents left = travsright;


poed A tour =mun


,
10 30 35 40 60 E5 . . .

suec
µ Sunbeam Infotech www.sunbeaminfo.com
find tra
t 4
5
]

9
2 → I → 6 → 4 →

fjF↳q÷±÷±±::s÷
diff = fan

m =
.tw#.data-trav.deta ;
new
rhrlecdi.FM ;

Sunbeam Infotech www.sunbeaminfo.com


Thank you!
Nilesh Ghule <[email protected]>

Sunbeam Infotech www.sunbeaminfo.com


Data Structure & Algorithms
Sunbeam Infotech

Sunbeam Infotech www.sunbeaminfo.com


BST -

post order C)

stack
50 &
toov= root
;

whilectravf.nu/l!sisEmrtytDEwhileCtoavl.=snwDE

30

90
✓ spushftrav) ,

40 70 100
ztouv-trav.leffjiffl.s.is
Empty {
10

tsav-s.popdjifctoav.right.knulldd.ltrav.rig.int

✓ r ✓

.
visited )E
20

60

80 s -
push ( trad ;

travntrav . right;
}

Eprintctrav.datditrav.vn
else

sited -_ true;

SQ70 1GQ trav=nuH ;


90 50 3
-

3
I
Sunbeam Infotech www.sunbeaminfo.com
skewed BST → man height
root

1
7dm Balanced BST
70
0cm) min height
/ X
.
.

69 root
man = 7
×
j
itrs 1 man =3
go 40
.
× its
/ I \
× 20 60

×
IF } .
I 7 .

20
.

/ ×

Ice
.
X
Skewed Binary Tree
-

70 10 • In Binary tree if only left or only right


links are used, tree grows only on one
60 20 side. Such tree is called as skewed
binary tree.
• Left skewed binary tree
50 30 • Right skewed binary tree height
&
• Time complexity of any BST is O(h).
40 40 • Such tree have maximum height i.e.
same as number of elements.
30 50 • Time complexity of searching in skewed
BST is O(n). → list
like linked
20 60
✓ v

10 70
Sunbeam Infotech www.sunbeaminfo.com
Balanced BST
bf 6 bf=2
bf=4
-_

-7
70 • To speed up searching, height
To s⑨ &of BST should minimum as

Yay
bf=a

§ !
⑤ ①
possible.
9. ¥9
60
-40 ②
* • If nodes in BST are arranged
so that its height is kept as less
30
5g
-

50 as possible, is called as
36 % 26 Go =Balanced BST.
16 • Balance factor
40 % to
if
-

• = Height of left sub tree Height


1£ 40
of left sub tree
Fight
30 • In balanced BST, BF of each
bf= 4%5=-2 bf=
-

node is -1, 0 or +1.


-

20 John 20 60
20 • A tree can be balanced by
b¥ 1%0=0 Ice bf=Q . bf=o applying series of left or right
rotations on unbalanced nodes.
10 To 10 30 50 70
Sunbeam Infotech www.sunbeaminfo.com
height 2 height =3
=
h+ ,
D= 2 -
1 A
40 I I
I
2h
B
/ c
Go deaf nodes 1)
Ift
20 =

I Cexteonae)
/ D E
/ ,
to 3050 70
naffodeggf = 2h - I H%fIFmIo
Cinternal)
9=7 = 15

deaf = 8

non -
leaf = 7
Right rotation
root →
40 root z

.J§
N
axis
20

20 60 Es ia tea
new
1 1
30 60

10 30
um

newaais axis left


;
.

right ;
/ A
axis left
.

= new axis .

I 77
new axis .
right = anis ;

if Canis = = roots

root = new ants ;

=
Sunbeam Infotech www.sunbeaminfo.com
Left rotation
'
40

20 60

50 70

Sunbeam Infotech www.sunbeaminfo.com


bf =-3
bf = 3
@ ace

I =/

arm

1 1
3@
30

2- f- D= 3
Rotation cases

z y
i.
In
a z
L
y .
.


x

Left-Left case
I
=

Sunbeam Infotech www.sunbeaminfo.com


Rotation cases

③ -
I\
?
y
r
"

x W

Right-Right case
= =

Sunbeam Infotech www.sunbeaminfo.com


Rotation cases
27 se


z 1 / I
left - take right rotate z
Y
×
y
y z

R
- I - ÷
.

Y '
.

W
x .

:
W
w

Left-Right case
- -

Sunbeam Infotech www.sunbeaminfo.com


Rotation cases

z R zf se

right I
left 1 I
rotate
y rotate z
y
L

a

:
I
- -

x y
w

'
r

w ÷

Right-Left case

=

Sunbeam Infotech www.sunbeaminfo.com


70 I 60 60
60

Y I I / I
I 1
60
50 70 ④ 70 40 70

Y
50
Y % Ya
40
4
30

~
60 40
Y I /
I
70 30 6@
4
'

I
% ↳ 20
so
II
/
' '
Ii 79
20
meo
AVL Tree

• AVL tree is a self-balancing Binary 2h = n

Search Tree (BST).


2 log n
• The difference between heights of left h log =

and right subtrees cannot be more


than one for all nodes. h =
lost
• Most of BST operations are done in dog 2

O(h) i.e. O(log n) time.


Th
-

h
• Nodes are rebalanced on each insert
operation and delete operation.
T a lost
• Need more number of rotations as log 2
compared to Red & Black tree.
oClo
Sunbeam Infotech www.sunbeaminfo.com
Threaded BST

50 50 • Typical BST in-order


traversal involves recursion

T.ir
-
or stack. It slows execution
30 30 and also need more space.
90 90
• Threaded BST keep address
of in-order successor or
40 70 100 10 40 70 100 predecessor addresses
10 instead of NULL to speed up
in-order traversal (using a
20 loop).
20 60 80 60 80
• Left threaded BST
• Right threaded BST
• In-threaded BST
Teftxhright
Sunbeam Infotech www.sunbeaminfo.com
Strict Binary Tree
- -
Perfect Binary Tree

÷
A

B C B C

11/1
D 2
E F G D E F G
×

11×11
H I J K ← H I J K L M N O
x x ×
x

• Binary tree in which each non-leaf • Binary tree which is full for the given
node has exactly two child nodes. height i.e. contains maximum possible
-

nodes.
2h 1 2h
- "
• Number of nodes = % p -

Sunbeam Infotech www.sunbeaminfo.com


A A A A
/ / / I 1 I
I I
B B C B
B C C C

5¥ It 5¥ It 5¥ It 5¥ It
n' ¥1 L 's I 1st
"

Is II
strict strict strict X strict ×
complete complete X complete ✓

almost cenobite X ✓ almost complete

Sunbeam Infotech www.sunbeaminfo.com


Complete Binary Tree and Heap
1
A • A complete binary tree (CBT) is a binary
2 3 tree in which every level, except
B C possibly the last, is completely filled, and
all nodes are as far left as possible.
4 5 6 7
• Almost complete binary tree is similar to
D E F G CBT, but may not be strictly binary tree.
8 9 10 parent =
child 12
92
H I J left child = parent
+ I
• Heap is array implementation of
right child parent
a
2
=
complete binary tree.
• Parent child relation is maintained
✓ V J J through index calculations
• parent index = child index / 2
A B C D E F G H I J
• left child index = parent index * 2
1 2 3 4 5 6 7 8 9 10 • right child index = parent index * 2 + 1

Sunbeam Infotech www.sunbeaminfo.com


used implement
Max Heap & Min Heap →
to
priority queues .

80
1 ↳ueldegue 8
1

2 3 0( log a) 2 3
17 35 17 10

4 5 6 7 4 5 6 7
15 10 20 30 25 40 15 12

8 9 10 8 9 10
12 2 1 35 26 43

Min
• Max heap is a heap data structure in • F-
Max heap is a heap data structure in
which each node is greater than both which each node is smaller than both of
of its child nodes. its child nodes.

Sunbeam Infotech www.sunbeaminfo.com


Heap Sort

1
17
2 3 dos )
0 (n n

HeapSo

15 12
heap ; → 0cm dog n )
4 5 6 7 ① make
more

1 10 2 20 is not empty )
② while ( heap
8 9 10 from heap ; → ocdogoy
del ele
30 35 80 ocne.sn Put val at end ,

<

17 15 12 1 10 2 20 30 35 80

1 2 3 4 5 6 7 8 9 10

Sunbeam Infotech www.sunbeaminfo.com


8 3 9 I 5 7 26 4
Merge Sort d. Montt so

0 1 2 3 4 5 6 7 8

8 3 9 I 5 7 26 4

9
-?
-
>
1 3 58 9 2 46 7

A f.
6 7 89
temp
-
: I 2 3 45
I K

Sunbeam Infotech www.sunbeaminfo.com


I m on -11 I

Merge Sort
& on mti I
0 1 2 3 4 5 6 7 8

8 3 9 I 5 7 26 4

- -

2 7 4 6
>

temp den ;
ite) 1 .
f.
is
-

footie ;
a→Cdeffti3= temp G) j a i 2 3

temp : 2 4 6 7

Sunbeam Infotech www.sunbeaminfo.com


Merge Sort
to
-m=up5 0 1 2 3 4 5 6 7 8

±÷ s ,
top : I 2 3 45 6 7 8 g

Sunbeam Infotech www.sunbeaminfo.com


Thank you!
Nilesh Ghule <[email protected]>

Sunbeam Infotech www.sunbeaminfo.com

You might also like