0 ratings 0% found this document useful (0 votes) 22 views 7 pages Data Structure and Algorithms
The document outlines various data structures and algorithms, including stacks, queues, and tree traversals (preorder, inorder, postorder). It provides definitions and examples of basic stack operations and traversal methods for binary trees. Additionally, it discusses search algorithms and graph theory concepts such as adjacency, paths, and trees.
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
Carousel Previous Carousel Next
Save data structure and algorithms For Later Stack > last ‘m first ont
= Stack(): Make an empty stack
= empty( ): Retum true ifthe stacks empty: otherwise,
= push(val: Ald the tem val tothe top ofthe stack
= pop( : Remove the top (most recenty added) tm rom the stack and the
deleted value is returned
= top(): Retum the item most recently added tothe stack, but do not remove it
turn false.
EXAMPLE: ONE(S)
FF Include 6 basic stack functions here
‘This algorithm retums True ifthere is
‘exactly one elementin the stack S.
ef one(S):
Otherwise, itretums False. The code fara
sos he sbstet data ype stack vaTStop) ute dot naaon
+ Before and ater sung he funcion Son no
One(S). tha content ofthe stack Sis he | S20 Seo
same, retum flag
+ makes use ofthe 5 basic ncons of
the ADT stack to complete the task. $= Siack()
‘S.push(1)
‘S.push(2)
‘S.pop()
prions) #Twe
Queue > Fest in Pest ont
= Queue( ): Make an empty queue.
<— = enqueue(val): Add the item val to the rear of the queue.
= dequeue( ): Remove the item from the front (least recently added) of the
queue. The deleted value is returned.
® front{ ); Return the item from the front of the queue, but do not remove it.
‘TREES: TERMINOLOGY (2)
Tis isa genera ooted toe
Root noe wiht parent
tena: wt st east ona cA, 8, C.F)
* staal node ortety roc winx chron
+ (SRTTBERHBHR2ogoncarers, rns
Depth ot node: umbet ances 2 ERAS 2
Hel ofa tae: maximum sort of ay 2086 (69, 2) Sui
Degree Te sunber cian at nae F2b0a) ata)
Subtee o0coniing of noob adits
(n-pin-2)... 1) =(r-0!PREORDER TRAVERSAL
Preorder traversal ofa binary tree rooted at root is defined by the rules:
root's empty, stop.
Visit root
Execute preorder on the binary
‘tree rooted at the left child of
the root.
4, Execute proordoron the binary
‘tree rooted atthe right child of
the root.
ere
Lensubiee —Rigntsubtee
¥ iia preorder traversal, a node is
visited before its descendants |v In short, oot—left— right
INORDER TRAVERSAL
Inorder traversal ofa binary tee rooted at root fs defined by the rules:
‘EXAMPLE: INORDER TRAVERSAL
1. ifrootis empty, stop.
12. Execute inorder on the binary
tree rooted at the left child of
the root.
3. Visit root.
|4. Execute inorder on the binary
tree rooted at the right child
of the root. ere est MM) 8 = 12.4,1.6,5,7.91
Leftsubtree Rightsubtree
“in short, left—root— right
POSTORDER TRAVERSAL
Postorder traversal of a binary tree rooted at root is defined by the rules:
41. Ifrootis empty, stop.
2. Execute postorder on the
EXAMPLE: POSTORDER TRAVERSAL,
binary tree rooted at the left i SReceierh.
CHIR OL the oe 3 ote
3. Execute postorder on the Plt 1 a ™
binary tree rooted at the right eee
child of the root. ne
4. Visit root,
Loft-subtree Right subtree
¥ In short, left—right—rootarrays
\
Sequential Search: Python code “ ry Search: Python code 1
‘et binary_searci(L bj Ke) °
def sequential_search(t, see ge re Ake at wen me
acto tag for ein ange(len(L)): ep bee nee
sects: (ERLE my cornea
aa = i: (ey Se UK) vag sawn
waaite B array index of the key mene]
corer ‘nerf amet er Dak ny et agape Mi at
Se 7 ene a fig)
-43,7,037\_ reel rr 7
7 tm
‘sequential search, key) Yet maga i mm
Printreaut) nr eran net nc ey Ls 65.33,28557
sequential search, key)
Print(result) ponies ey
Perera ar serc tn
fae print(result)
te
| a &
Prt
= accu ong
Adjacent vertices oa arm
= U and V are adjacent (one-hope away) y n2k=1 = 2k=n es ae
A BagHae of a vertex et za
aD of 2 vor SS pean oe = log(n) me
Pee ee eee Time complexity = O(log(n))
Parallel edges
© hand i are parallel edges
Simple graph
O Self-loop
© A graph with neither selftoops
nor parallel edges {an example of
jis. selfloop Parallel edge An exam
O Path er
sequence of alternating vertices
and edges,
~ begins with a vertex
» ends with a vertex
cycle
Apath whose inal vortex and
QA graph is called a tr
contains no cycles
A tree with n vertices has n-1 edges
© proof not required
if it is connected and it
XG. W.6.U.85V) isa
edge ave nea
© C2(U.0.V.0,0) fs nota cycle
Not a tree A tree Not 0 tree
qf S opey
Hocoobly
mooos|h
1
0
1
0
1
0
wenn
ee
0 mc [ety
adyacency ist
5: (1:55, 3:23)
}start toa: i cont host
Q wmansuaieT iine Trace __ brad. Bs
TRatteve te ontvatte ota, '*— cin the worst case
call itv and add v to vist yea”
Remove v froma v "We have to visit all vertices, which takes
1 Add a unvisted Ea a O(n) time
adjacont vertices of y tog cams “We have to visit all the edges to explore
ce adjacent vertices, which takes ‘Olm| time
GCI “Hence, the overall time complexity of BFS
is O(n+m)
4D ereH Aco
‘ 6 F on” Apcoer
7 em Amcoere
8 Wu ABcDERON
213 ApcpereH
os KL ABeDEFONIS
ot ABERERGHIIKKdof siftup_recurs(v, 4)
fie
return # Boze cat
parent_idx = 4 // 2
4 VE] > viparent_ idx)
VEE1, viparent_idx]
siftup_recurs(¥, par
rect has ne parent
Viparent_sde], v[i] # Swap with parent
mnt idx) # Recurse on the parent index
‘Base Case: I the node at index is the root (6. == 1), then there's no parent to compare with, so the heap property i trivaly satefied, and we can stop.
Find Parent Index: For any node at index its parents located at index i 2, Parent Comparison: For anyother node, the slgoithm checks if the nodes value
's greater than ts parents value. Ifo, i swaps the values to maintain the max-heap property.
jevses a shin
Rarer Sane 3
str_ien = len(a_str)
af strien or str_ien == a: ct
retrn ast 7e
else: ab shang
Jast = a_str[str_len - yh J
prlne(a srforsts tena)
fawstr ease + Fe op(ese[ossth_le-3D)
eee
pels (te strng)
pew eGring = rer op(the_string)
pedaeCnatserana)
Sing fos ash charter
sei,
mos
FE we
gnirts
‘The Node class represents each node in the Linted List,
fmvith dato storing the value and next pointing to the next node in the sequence.
lacs Node
def init _(self, datecnone, next_node-none):
Toit cata = ata
self.oext = next_node
stris function takes tuo paranetens: header (the storting node of the Linked List)
ftand & (an enpty List to store the copted deta)
ef copy_eata(neader, A):
eager
While current 4s not None:
‘A.append(current.data) # The data from the current node is appended to the List &
‘count += 1 #7he count voriable is incremented by 1 for each node processed.
‘current = current.next #7he current pointer iz updated to current.next to move to the next node in the Linked List.
return count #The function returns the total count of elements copied, which is the number of nodes traverseddef besl graph, art)
Visited [False x (ln(grapo+1))
quene = 03
Araversal order = LI
qene ‘append (start)
Visited (start) = Te
while qmene:
Vertex = qmene. popl)
NowerSal_ ordey. append (vertex)
$Y neighbor ia gyaphlieees:
if not visited [neighbor]
apne Appencl neighbor)
Visited (heighbor} = Te.
Tetwin faversal— order‘wipor+ heapy,
Class Cnraph:
det Dijkstra (selt, sre)
fr neighbor , weight in Sep -acjacemag-list neispar]. eons ()