Data Structures - UNIT 3
Data Structures - UNIT 3
Trees
Definition:
ii)the remaining nodes are partitioned into n disjoint sets T 1, T2, T3, .........Tn where T1,
T2, T3, .........Tn are called sub trees.
Example
Terminologies:
Node: Node of a tree stores the actual data and links to the other node.
Root node: A first node written at the top is root node. The root node does not have the
parent.
Child: The node obtained from the parent node is called child node.
Predecessor: Every node N in a tree except root has a unique parent called as predecessor of
N. Here B is the predecessor of D, E, H, I and J.
Successor: Every node N in a tree except the leaf nodes has a unique child called as
successor of N. Here D, E, H, I and J are the successor of B.
Siblings: Two or more nodes having the same parent are called siblings. Here D and E are
siblings since they have same parent B.
Ancestors: The node n1 is said to be an ancestor of other node n2 if n1 is either the father of
n2 or the father of some ancestor of n2. Here A is the ancestor of B, D, E, H, I.
Descendant: The node n1 is called the descendant of node n2, if the node n2 is reachable
from n1. Here H is the descendant of D, B, A.
Degree: The number of sub trees of a node is called its degree. Here the node B has two sub
trees. So, degree of node B is 2.
Level: The distance of a node from the root is called level of the node. (or) Level is the rank
of hierarchy. The level of root node is 0.Here the level of D is 2.
Height (Depth): The height of the tree is defined as the maximum level + 1 of any leaf in the
tree. Here height of D is 3
Forest: A forest is a set of disjoint trees. The representation of forest is similar to tree.
Example in the above figure if we remove the root of tree a forest is created with 2 trees
headed by node B and C as root.
Binary Tree:
i)T is empty or
iii) the remaining nodes of T form only upto two disjoint binary trees T1 and T2 which are
called the left sub-tree and right sub-tree.
Strictly binary tree is a binary tree that has non-empty left and right sub trees. The out degree
of every node is either zero or 2.
A complete binary tree is a binary tree, which is completely filled, with the possible
exception of the bottom level, which is filled from left to right.
ii)For any node in the tree with a right descendant at level n, the node must have a left child
and every left descendant of node is either a leaf at level n or has two children.
A binary tree data structure is represented using two methods. They are:
1. Array Representation
2. Linked List Representation
To represent a binary tree of depth 'n' using array representation, we need one dimensional
array with a maximum size of 2n + 1.
Advantages
1. It is suitable for complete binary tree
2. Efficient if the tree does not go for changes such as insertion and deletion
Disadvantages
1. Not suitable for normal binary trees
2. It uses static allocation so that leads to memory wastage.
Example:
Advantage
Disadvantage
1. Extra memory is required to maintain the left link and right link pointers
Traversal is a process of visiting each nod exactly once in a systematic order. Binary tree has
three types of traversals.
1. Preorder
2. Inorder
3. Postorder
1. Preorder Traversal
The preorder traversal of a binary tree can be recursively defined as follows:
• Process the node data (D)
• Traverse the left subtree in preorder (L)
• Traverse the right subtree in preorder (R)
Algorithm:
Call pre_order(ptr->left)
Step 3: Traverse the right sub tree recursively in preorder
If ptr->right ≠ NULL
Call pre_order(ptr->right)
Step 4: return
Explanation:
Using the above algorithm we write the preorder traversal of the below binary tree.
2. Inorder Traversal
The inorder traversal of a binary tree can be recursively defined as follows:
• Traverse the left subtree in preorder (L)
• Process the node data (D)
• Traverse the right subtree in preorder (R)
Algorithm:
Print ptr->info
Step 4: Traverse the right sub tree recursively in inorder
If ptr->right ≠ NULL
Call in_order(ptr->right)
Step 5: return
Explanation:
Using the above algorithm we write the inorder traversal of the below binary tree.
Step 1: It visit the root node. It check left node is NULL or not. Here it has value 5
Step 2: It visit the node 5. It check left node is NULL or not. Here it has value 9
Step 3: It visit the node 9. It check left node is NULL or not. Here the left child is NULL.
Step 4: So it process the data.
Step 5:Recursively it call in_order() until all the node has been visited.
3. Postorder Traversal
The postorder traversal of a binary tree can be recursively defined as follows:
• Traverse the left subtree in preorder (L)
• Traverse the right subtree in preorder (R)
• Process the node data (D)
Algorithm:
Call post_order(ptr->right)
Step 4: Process the root node.
Print ptr->info
Step 5: return
Explanation:
Using the above algorithm we write the postorder traversal of the below binary tree.
Step 1: It visit the root node. It check left node is NULL or not. Here it has value 5
Step 2: It visit the node 5. It check left node is NULL or not. Here it has value 9
Step 3: It visit the node 9. It check left node is NULL or not. Here the left child is NULL.
Step 4: So it process the data.
Step 5:Recursively it call post_order() until all the node has been visited.
Explanation
Using the above create procedure we construct a binary search tree. Let the data are
56, 38, 10, 65, 72, 44 and 50
Step 1: Create the root node
5
6
Step 2: Take the second element 38, which is less than 56. So create a left child.
Step 3: Take the third element 10, which is less than 56. So go to left of 56. 10<38, so create
a left child.
Step 4: Likewise it compares value and node and add the node in corresponding order.
3 6
1 4 7
5
Tree Search
Searching an item in a binary search tree is finding the element in the tree. It is faster than
searching in binary trees, arrays or linked list.
• An AVL tree is a binary tree in which the heights of the left sub tree and height of the
right sub trees of the root differ by at most 1 and in which the left and right subtrees
are again AVL trees.
• The structure of an AVL tree is same as binary search tree additionally it balances the
height using balance factor
• Search
• Insert
• Delete
AVL Rotation
Rotation is the process of moving nodes either to left or to right to make the tree balanced.
There are four types of rotations depending upon where the new node is inserted.
Left to Left rotation: When the pivot node is left heavy and the new node is inserted in left
sub tree of the left child of pivot node then the rotation performed is left to left rotation
Right to Right rotation: When the pivot node is right heavy and the new node is inserted
in right sub tree of the right child of pivot node then the rotation performed is right to right
rotation
Left to Right rotation: When the pivot node is left heavy and the new node is inserted in
right sub tree of the left child of pivot node then the rotation performed is left to right rotation
Right to Left rotation: When the pivot node is right heavy and the new node is inserted in
left sub tree of the right child of pivot node then the rotation performed is right to left rotation
• Step 1 - Insert the new element into the tree using Binary Search Tree insertion logic.
• Step 2 - After insertion, check the Balance Factor of every node.
• Step 3 - If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
• Step 4 - If the Balance Factor of any node is other than 0 or 1 or -1 then that tree is
said to be imbalanced. In this case, perform suitable Rotation to make it balanced and
go for next operation.
Consider an AVL tree by inserting the following elements in the given order
63, 9, 19, 27, 18, 108, 99, 81
Example
Construct a max heap tree with the given data values: 25, 35, 20, 10, 45, 70, 50
The following steps are involved deleting a node from the heap tree
Heap Sort
Heap sort is one of the sorting algorithms used to arrange a list of elements in order.
Example
Trie: Definition
• Trie is an ordered tree data structure that is used to store a dynamic set or associative
array where the keys are usually strings.
• It is a tree of order m either empty or consisting of an ordered sequence of exactly m
tries each of order m.
Trie is a special data structure used to store strings that can be visualized like a graph. It consists
of nodes and edges.
• Each node consists of maximum 26 childrens and edges from parent to children
• 26 pointers are 26 English alphabets.
• Strings are stored in top to bottom fashion.
• All prefixes of length 1 stored at until level 1
• All prefixes of length 2 stored at until level 2 and so on.
Example
Advantages of Tries
• Faster Search
• Less space
• Longest Prefix matching
Disadvantages of Trie
• Some cases trie is slower than hash table while searching data.
Applications of Trie
• To store a Dictionary
• Spell-checking software
The process of searching for data from external storage (outside memory) is known as
external searching or external memory searching. Example: B-Tree
B-Tree
• A B-Tree is a self-balancing m-way tree data structure that allows searches, accesses,
insertions and deletions in logarithmic time.
• Each node in a B-Tree of order m can have at most m children and m-1 keys
B-Tree Properties
• Every node in the B tree has at most m children and m-1 keys
• Every node in the B tree except the root and leaf nodes has atleast m/2 children
• The root node has at least two children if it is not a leaf node.
• All leaf nodes are at the same level
B-Tree Operations
• Searching
• Insertion
• Deletion
• Step 1: Search the B-Tree to find the leaf node where the new value or key is to be
inserted.
• Step 2: If the leaf node is full, (it already contains (m-1) keys)
1. Insert the new key into the existing set of keys in order
2. Split the node into two halves
3. Push the middle element upward to its parent node. If the
parent node is full, then split the parent node using the step 2
procedure.
• Step 3: If the leaf node is not full, then insert the new key into the node, keeping the
elements in the order.
2. If the node has a minimum number of keys, then first we will check the number of
keys in the adjacent leaf node.
a. If the number of keys in the adjacent node is more than the minimum number
of keys, then the first key of the adjacent leaf node will go to the parent node,
and the key parent in the parent node will be combined together in a single
node.
b. If the parent node has less than the minimum number of keys then the same
steps will be repeated until we get a minimum number of keys
• The key from the node is deleted, and its place will be occupied by either its successor
or predecessor key
• If both predecessor and successor nodes have keys less than the minimum number
then the keys of the successor and predecessor are combined
Consider the B tree of order 3 given below and perform the following operation a) insert
122, 88 and b) delete 37, 110
Application of B-Trees
Applications of trees
I qnyh.
qsarA q h -l
1.otur ) and a ao.t F o5
:+' ) b"la
atuyt
4=(v,tt
+u'fu,a
y=\ A,a,(,D J
E - \ h 'r,'
( ( h't )
'(B 'c) '(c 'D)
j D
?.-Diwh.t qne,Fh,
stba^df
fl'^f
ca[b"l s,L
r" (v 1
tt "[
f.Y
q E ) t'th k"t
y)cr
fftu
B,nd €t!€
1Lt )
ta) suLo1ta,ph
l
, ,ojou,', ad -1
"tub"t ,"atkur
, .' -l vorh,
ru/1 t^t rclt h t i ,11
i,-And,u t i .>
a*Jq,, t) ,
r]trF.{r[,iu!I))= r
lnc|a", a*zb/.,u3). 3
- "u re,
1nc{.?
ap
(,). 2 ul c!|1,or t n) = a
1 'DcX
*o (t). h
,*a (:l :
[*) ' z
"i
fl,"!,h ;t trr
ffi, lalflorL drl tt"
"t.t j 'f
Lo tlat
T"fh
r& h
Plrt,
I
h sinyb C,t i! .sa; d Lr ha t''Pbtt i7
nw7'1,
wr&>r q ts
I 1
I
fl
Pl k" t
3
kr [n t-!
4
ShonaL c"\,hs
hn "nclr*tctad
L ca llt rl ct'D ckd ial
?
0(!t"J ftu, cl \athta, ff,oa rtrt-
1or
1kr'
L
)
-t
.3 p)
o
to) tomtttad ctrxa7h Ir] ,51,onfu tearrc c h'l pr
x*
ta NLi
n fl'"Ph
h contishEowLv$
wo i,,1
Jal: E oi
, ,r
rx,, and LLbiflhb 6w ',rlt.n,"l
lo cr,o' Or1
1"
v
4 ( 5
t9
?
tr . PoFl, ,
Pok^ b
Vo l. Vl1 q ra.,!th
srL,tr nu a ""tf
hT
:[-::i,. vo and ot c!;.3
\vo,a ,u ,u,ur, vn-, , o6,v" ]
2
fl
,"p1, *ttt "" ,,1'1"
LI t,
tl. L
A,) ,+ I t) t
h wh;6 sta,Ls ,,.,,c1 an{'
nl +fu J4h.! !'elt.). i5
n""r
!;a"" ,lah s,l,u,t.e.
b,. btnraon LL'diJ\ l;. r,t7atent 4 1/LarL.
t.hd1acer,cttr
A h.tjacc ^.,1 l,s t
,l na-ti t :
^di
-]I'c d*a.rrtL,l nv-h,ix , t o, nak,x wi.
u:fun T]"re
a- d t j)
o.ltr -tfu
r
1,*
d
fl'"rh
&u t6,l X
L utn
Fo, u.,d;r*c l,d q
fl fA
i.(;,l) 6E o, (j i\€ E
ndt"i x = A(i,i)=
4 1
o a&,Y ui+e t
trot a Jiutt d q
T16
llti,.l)eE)
hd.1au nt1 matvix , A( | ,i) .\
to uLored
hfr Q (,,,rr
x
fr.t
t1
j hh l-
ncLH bl',"J
:l
d4ii.ili, n .
w(,.,j) I( ,j) c€
h(i,i J -
hcljout c;1 n atr,'c =
I & Atl*t oigz
+
Llnd,,r,. Ld Di.&,hd t
A.tj"uh.l hatu t x
4 1
h
I o lo I alo
2 I ol z
3 I o
3 oooo
lf r0 ooio
[lar h larl
nllyun1 fi, ,,
') 3 +
I
L ,
3 3
l
z hdt
?n
", ^:'J Ltt r,e ptatt"taho" #, arth vc,hr in
.
tLt
?^l)'
Ael ctcab,l lt; atorc- all
)< 1t,,
1 1 l''^hr
Gnlad Ls[ c,r"os ,J +hr adAarq.,l
'f
t" eat l, ,c,hx i" 1A" f,
*t1 t,1 F
4 h1
aa1 tt [@
afitu) 5
^ct1l51
U*,clil,ttnl Gnnrl"
4t,1
3
a,t; h1
agkl I
aditLl
rl E,[@
4hr
UNIT 3 Data Structures Using C 31
A vertex in an undirected connected graph is an articulation point (or cut vertex) if removing
it (and edges through it) disconnects the graph.
Biconnected graph
1) It is connected, i.e. it is possible to reach every vertex from every other vertex, by a
simple path.
2) 2) Even after removing any vertex the graph remains connected. (No articulation points
in the graph
Graph Traversal
Graph traversal is a technique used for a searching vertex in a graph. That means using graph
traversal we visit all the vertices of the graph.
There are two graph traversal techniques and they are as follows...
Algorithm
Breadth First Search is a traversal technique in which we traverse all the nodes of the graph in
a breadth-wise motion. In BFS, we traverse one level at a time and then jump to the next level.
The BFS algorithm makes use of the queue data structure for implementation.
Procedure
Algorithm
Topological sorting
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such
that for every directed edge u v, vertex u comes before v in the ordering. Topological
Sorting for a graph is not possible if the graph is not a DAG.
Example
Algorithm