0% found this document useful (0 votes)
465 views

(Nonlinear (6-31) : Structures GTU-Sem. 3-Comp/T) Binary Tree

The document discusses binary search trees and includes examples of: 1. Constructing a binary search tree from a given sequence of numbers and performing postorder traversal. 2. Generating a binary search tree for a given set of numbers and performing inorder and postorder traversals. 3. Creating a binary search tree for a given data set and labeling the nodes.

Uploaded by

BHAVESH
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
0% found this document useful (0 votes)
465 views

(Nonlinear (6-31) : Structures GTU-Sem. 3-Comp/T) Binary Tree

The document discusses binary search trees and includes examples of: 1. Constructing a binary search tree from a given sequence of numbers and performing postorder traversal. 2. Generating a binary search tree for a given set of numbers and performing inorder and postorder traversals. 3. Creating a binary search tree for a given data set and labeling the nodes.

Uploaded by

BHAVESH
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/ 25

Structures GTU-Sem.

3-Comp/T)
(NonlinearData Structure)...Page no. (6-31)
Date

Element
Binary Tree

45

56

39

12

4s)

binary search tree for given sequence and


GO. Draw a
1058976215.

write postorder traversal oftree.


34
(4Marks)

78

Post-order Traversal

2,6,7,9,8, 5, 15, 10
for the followin9
***

tree
.Construct a binary search
inorder and postorder
Sequence. Also do the
:
traversal for the same
34, 78, 54, 67, 10, 32, 54
45, 56, 39, 12, GTU-S-14, 7 Marks
,81 - - - - - * * * *

***-------.

Tech-Neo
Publications.A SACHIN SHAH Venture
(G3-01)
GTU-NewSylabus w.e.f.academicyear 19-20)
*
Data Structures (GTU-Sem.
3-Comp/T) (Nonlinear Data Structure)..Page no. (6-20
32
45
(56)
67
81 18

10 (34) 67 89

56 GQ. Generate a binary search tree for following numbers


and perform in-order and post-order traversals
10
(7 Marks
1 50, 40, 80, 20, 0, 30, 10, 90, 60, 70.

50

40

39
(50
32 4)
80

(50
20 (A0 (80)

89
89

10 (89 (A0) 80
0

SHAHVent

(GTU-New Syllabus w.e.f. academic year 19-20) (G3-01) Tech-Neo Publications...A SAC
ructures (GTU-Sem. 3-Comp/1T) (Nonlinear Data Structure)....Page no. (6-33)
D a t a

70
50 (50)
(80)
(20) (80)

50)
In Order -0 10 20 30 40 50 60 70 80 90
80)
Post Order 100 30 20 40 70 60 90 8050
10 (20 In Order - 0 10 30 0 40 50 70 60 80 90

Ua. Create a binary search tree for the following data.


14, 10, 17, 12, 10, 11, 20, 12, 18, 25, 20, 8, 22, 11, 23
GTU-S-18, 4 Marks
-

1) 14 2) 10

60
40 (80 10
3) 17 4) 12
90 (20
1
(10)
12
60
5)10 6) 11

(80
20 60 10
(90
10
10)

U-New Syllabus w.e.f..academic year 19-20) (G3-01) Tech-Neo Publications...A SACHIN SHAH Venture
Data Structures (GTU-Sem. 3-Comp/IT) (Nonlinear Data Structure no. (6-3A
7) 20 8) 12

14 11) 20

(10) (10 (
(12) 10

(10 (12 (29


(11) (12) 19
9) 18

12) 8

10 19)

(10

(1) (10
10) 25

13) 22

10) (1)
10

10) 19 (12) (
(1) 10
12 (18) (
20

GTU-New Syllabus w.e.f. academic


year 19-20) (G3-01)
Tech-Neo Publications..A
..A SACHIN SHAH Vent
Structures
(GTU-Sem.3-Comp/IT) (Nonlinear Data Structure)...Page no. (6-35)
Data

3) 30 4) 60
14) 11

30
(10)
60)
0

5)15 6) 75

2 ( (5
(20 19
(1) (2 60
15) 23 7) 35

(10 30

8) 55
(10) 25
(20

****

a. Create a Binary Search Tree for the following data


9) 20
and do Inorder, Preorder and Postorder traversal of||
the tree.
45, 70, 30, 60, 15, 75, 35, 55, 20, 85, 80

GTU-W-18,7 Marks (70


- ************

) 45
2) 70
60

20

STJ-NeW Syllabus
SylR w.e.f. academic year 19-20) (G3-01) Tech-Neo Publications ..A SACHIN SHAH Venture
Data Structures (GTU-Sem. 3-Comp/TD (Nonlinear Data Structure)....Page
10) 85
no. (6-36
5) 12 6) 15

45

(30)
(10) (14
1 (35 60

20 (85 7) 16 8) 7

11) 80

14
(30
13) (60

9)9
20

(14)
Preorder: 45,30,15.20.35.70.60,55,75,85,80

Inorder: 15,20.30,35,45.5560,70.75,80,85
Postorder: 20,15,35,30,55.60,80,85,75,70,45
- - .

Ua. What is Binary Search Tree? Construct a binary


16
search tree for the following elements. 10) 23

GTU-W-18,7 Marks
2) 6
1) 11

(8) (
3) 14 4) 8

(2
(14) 1

Ventue
SHAH
(GTU-New Syllabus w.e.f. academic year 19-20) (G3-01) Al Tech-Neo Publications A SACHIN
D a t e

(GTU-Sem. Comp/T)
S t r u c t u r e s( G T U . S s

(Nonlinear Data Structure)...Page no.(6-37)


LECTURE-6
Algorithm to delete Node with one child
s y l a b u sC o v e r e d

Slep I: Find the node to be deleted using search


peletion Operation in BST
to delete Leaf Node
operation
Step2 If it has only one child, then create a link
Algorithm

(0 Algorithm to delete Node with one child


between its parent and child nodes.
Algorithm to delete node with two children Step3: Delete the node using free function and
( terminate the function.
cFunctionto delete nodefrom BST
It this case, node is removed from the tree and
6.7.4 Deletion Operation in BST algorithm links single child (with it's subtree) directly
. * * * * * * -

to the parent of the removed node.


0. Write an algorithm/ Program to delete a node from
a binary tree. OR Explain deletion operation in BST. Example
ORWrite an algorithm for DELETE operation in a
Remove 18 from a BST.
Binary search tree.

TU-S-11,W-14, W-15,W-19 (New Syllabus), 7Marks


****

*******************---- -----.
, In a binary search tree, the deletion operation is
performed with O(log n) time complexity. Deleting a 1
node from Binary search tree has following three
cases

Case 1: Deleting a Leaf node (A node with no children)


Case 2: Deleting a node with one child
Case 3: Deleting a node with two children
Case 1: Deleting a leaf node
We use the following steps to delete a leaf node from
BST..

Algorithm to delete Leaf Node

Step 1 Find the node to be deleted using search


operation.
Step25 Delete the node using free function (If it isa
leaf) and terminate the function.
This case is quite simple. Algorithm sets corresponding
ink of the parent to NULL and disposes the node.
Lxample: Remove - 4 from a BST. Case 3 Deleting a node with two children
We use the following steps to delete a node with two
children from BST...

Algorithm to delete node with two children

Step 1: Find the node to be deleted using search


operation.
e 2: Step 2 If it has two children, then find the largest node
Deleting a node with one child
in its left subtree
We use the following steps to delete a node with one (OR) the smallest node in its
child from BST.. right subtree.

New Syllabus e.f. academic year 19-20) (G3-01 Tech-Neo Publications .MA SACHIN SHAH Venture
Data Structures (GTU-Sem. 3-Comp/IT) (Nonlinear Data Structure)...Page no ls.
Step 3 Swap both deleting node and node which found
in above step.

Step4 Then, check whether deleting node came to 19


case I or case 2 else goto steps 2.

Step 5 If it comes to case 1, then delete using case


logic.
Step 6 If it comes to case 2, then delete using case 2|
CFunction to delete node from BST
logic.
void deletebt ( struct nodebt **root, int num)
Step 7 Repeat the same process until node is deleted
from the tree.
intfound;
Example: Remove 12 from a BST.
struct nodebt "parent,*x, xsuce;
if(*root== NULL) If tree is empty

printf ( "nTree is empty")


12 return;

Call to search function


to find the node to be
parent = x = NULL ; deleted

Find minimum element in the right subtree of the node


searchbt (root, num, &parent, &x, &found);
to be removed. In current example it is 19.

if (found == FALSE)
if the node to deleted
is not found

printf ( "nElement not found");


return;

if(x->Lehild!=NULL &&x->Rchild!=NULL
If the node to be
parent X;
Replace 12 with 19. Notice, that only values are deleted has two
nodes. Now have two nodes with the
XSucc = x -> Rchild; children
replaced, not we

same value.
while ( xsucc -> Lchild != NULL)

parent XSucc ;
Xsucc= xsucc -> Lchild ;

X-nodedata = xsucc -> nodedata;

x XsucC

Remove 19 from the left subtree.

Ventue

(GTU-New Syllabus
w.e.f. academic year 19-20) (G3-01)
Tech-Neo Publications...ASACHIN SHAH
ctures (GTU-Sem. 3-Comp/IT)
D a t aS t r u c t u r e s ( G T U - S e n

n
(Nonlinear Data Structure)....Page no. (6-39)
Lchild == NULL && x -> Rehild== NULL
if(x count = count + inorder ( sr - > Lehild )

If the node to be deleted if (sr->right != NULL)


has no child count= count + inorder ( sr -> Rchild):

f(parent-> Rchild== x)

parent->Rehild= NULL return count;

else * * * - - - -

parent-> Lebild = NULL


GQ. Write a 'C' program to traverse the tree in in-order.
free(x) If the node to be deleted
relurn : has only right child
(4Marks)
void inorder ( struet nodebt *sr) Print the nodedata
of the node whose
f(x->Lehild == NULL && x -> Rchild!= NULL) Lchild is NULL or
if(sr!= NULL) the path has
already been
traversed
if(parent-> Lchild ==x) inorder ( sr-> Lchild);
parent>Lchild = x -> Rchild:
printf ( "edr"', sr -> nodedata)
else
inorder ( sr-> Rehild)
parent> Rchild= x -> Rchild;

free (x)
return, LECTURE -
Syllabus Covered
if(x->Lehild != NULL && x -> Rchild== NULL) Complexity of Binary Search Tree
() Program to perform operations on Tree
If the node to be deleted
has only left child (Gi) Conversion of General Tree to Binary Tree
6.7.5 Complexicy of Binary Search Tree
i f (parent > Lchid == x)

parent-> Lchild = x-> Lchild ;: GQ. Find complexity of binary search.


* - - - -

else
Consider following BST
parent-> Rchild= x ->> Lehild;
free (x )

return

. Write a program to count the number of node in a


-O
Searching: For searching element 1, we have to
binary search tree. GTU-W-16, 4Marks traverse all elements
(in order 3, 2, 1). Therefore,
nd inorder( struct nodebt sr) searching in binary search tree has worst case
Traverse a binary
search tree in a complexity of O(n). In general, time complexity is
alie int count= 0; LDR (Left-Data- Oh) whereh is height of BST.
Right) fashion
(st->left != NULL)
GTU-N Syllabus w.e.f. Tech-Neo Publications...A SACHIN SHAH Venture
academic year 19-20) (G3-01)
Data Structures (GTU-Sem. 3-Comp/T) (Nonlinear Data tructure)....Page no.
Insertion: For inserting element 0, it must be inserted
(6-40
2. printf'n 5: Post-order ");
as left child of 1. Therefore, we need to traverse all printf"'n 6: xit")
elements (in order 3, 2, 1) to insert 0 which has worst
printf'n Select your choice: ");
case complexity of O(n). In general, time complexity is
Oh). scanf"od",&ch);
3. Deletion For deletion of element 1, we have to switch(ch)
traverse all elements to find 1 (in order 3, 2, 1).
Therefore, deletion in binary tree has worst case
case J
complexity of O(n). In general, time complexity is
printf("in Enter element to insert: ");
Oh).
scanf('od",&ele):
Program to perform operations on Tree insertbt (&bt,ele);
break;
, Ga. Write a program for Binary search.
* * * * * * * * *
(7 Marks)
* * * * * * * * -
case 2

#include <stdio.h> printf('n Enter element to delete: ");


#include <conio.h> scanf("od"&ele);
deletebt (&tbt, ele );
#include <alloc.h>
case 3
#define TRUE 1
#define FALSE 0
inorder (bt )
break:
struct nodebt

case
struct nodebt *Lchild ;
preorder (bt ) ;
int nodedata;
break:
struet nodebt *Rchild;

case 5:
void insertbt (struet nodebt **, int );
postorder (bt );
void deletebt ( struct nodebt **, int ) ;
break;
void searchbt (struct nodebt **, int, struct nodebt **,
struct nodebt **, int * ) :
default:
void inorder(struct nodebt *); printf("nInvalid choice..")
void preorder (struct nodebt* );
void postorder ( struct nodebt *):

void insertbt ( struet nodebt **sr, int num)


void main() {
if(or == NULL)

struct nodebt *bt;


int num, ele, ch; sr malloc ( sizeof ( struct nodebt ) );
bt = NULL; Empty Tree
(r)->Lchild = NULL
clrser()
s r ) - > nodedata E num;
while (ch!=6)
(sr)-> Rchild= NULL;
printf('n 1: Insert ); Search the node to
else be
printf("in 2: Delete "): which new node will
attached
printf"n 3: In-order ");
printf("in 4: Pre-order "; if(num <( ar )-> nodedata)
Ventue

(GTU-New Syllabus w.e.f. academic year 19-20) (G3-01) Tech-Neo Publications...A SACHINSHAH
D a tSa

actures (GTU-Sem. 3-Comp/IT


r u c u r e s( G T U - S .

(NonlinearData Structure)..Page no. (6-41)


ertbt (&( (*sr)-> Lehild ), num ): if(x-> Lehild == NULL &&x-> Rehild== NULL)

else If the node to be deleted


insertbt ( &( ( r ) -> Rchild), num has no child

If new nodedata is
if(parent -> Rchild== x)
less, traverse to
left else to right parent > Rchild= NULL;
else

deletebt ( strict nodebt **root, int num ) parent-> Lchild = NULL;


i
free (x )
return
int found;
struct nodebt "parent, *x, *xsucc;
f(root= NULL) If tree is empty
if(x->Lehild== NULL &&x-> Rchild!= NULL)
If the node to be deleted has
only right child
printf ("nTree is empty" )
retum
Call to search function if (parent-> Lehild == x)
to find the node to be parent-> Lchild = x -> Rchild;
deleted
parent= x = NULL ; else
parent-> Rchild= x -> Rchild;

searchht ( root, num, &parent, &x,&found); free(x);


return; If the node to be deleted
has only left child
if(found == FALSE )
if the node to deleted
is not found

printf ("nElement not found") ; if(x->Lehild!=NULL && x -> Rchild== NULL)


return ;
i f( parent-> Lehild == x)

if(x->Lehild = NULL &&x-> Rohild!= NULL) parent->Lehild = x -> Lehild:

else
If the node to be deleted
parent X parent-> Rchild= x -> Lchild;
has two children
xSuce = x -> Rehild;

free(x);
while (xsucc -> Lehild != NULL) return

parent XSucC;
Xsuce = xsucc-> Lchild; void searchbt ( struct nodebt **root, int n, struct nodebt
**parent, struct nodebt **s, int *found )

X-nodedata =
xsucc -> nodedata struct nodebt "temp;
X XSucc;
temp= *root;
found = FALSE

W
Syllabus w.ef. academic year 19-20) (G3-01) Tech-Neo Publications ..A SACHIN SHAH Venture
(NonlinearData Structure). Page no (c
Data Structures (GTU-Sem. 3-Comp/T) 6-42
Output
parent NULL;
If the node to be L CiTREEL.exe
while ( temp!= NULL) deleted is found
Insert
nodedata n
Delete
if temp -> ==
3: In-or der
4: Pre-order
5: Post-order
found TRUE; 6: Exit choice : 1
Select your
s = temp;
returm

cONVERSiON OF GENERAL TREE


6.8
parent = temp; TO BINARY TREE
if (temp -> nodedata > n)

temp= temp -> Lehild; UQ. With a suitable example, explain steps for
else conversion of a general tree into a binary tree
temp temp -> Rehild; GTU- S-16,7 Marks
Traverse a binary A general tree can be changed into an equivalent
search tree in a
binary tree. This conversion process or technique
LDR (Left-Data
i

void inorder ( struct nodebt *sr) Right) fashion called the natural correspondence between general and

binary trees.

if(sr!= NULL) 2. The algorithm is written below

(a) Insert the edges connecting siblings from left to

inorder ( sr -> Lchild );


right at the same level.
printf ("odt", sr -> nodedata); (b) Erase all edges of a parent to its children excep
inorder ( sr ->Rchild);
to its left most offspring.
Print the
Rotate the obtained tree 450 to mark clearly let
nodedata of the (c)
node whose and right subtrees.
void preorder ( struct nodebt "sr ) Lchild is NULL or
3. A general tree shown in figure (a) converted into the
the path has
already been binary tree shown in (b).
if(sr!= NULL) traversed

printf ("%odt"', sr -> nodedata ) ;

preorder(sr -> Lchild);


Traverse a
preorder ( sr->Rchild); binary search
tree in a DLA
(Data- Left
Right) fashion
void postorder ( struct nodebt "sr)

Traverse a binary
if(sr!= NULL) search tree in a
LRD (Left-Right
Data) fashion
postorder (sr -> Lehild ) ;

postorder (sr -> Rchild); 0-


printf ("odt",sr -> nodedata);

academic year 19-20) (G3-01)


(GTU-New Syllabus w.e.f. Tech-Neo Publications.MA SACHIN SHAH Ver
Data
uctures (GTU-S 3-Comp/T) (Nonlinear Data Structure)..Page no. (6-43)
EXPRESSION TREE
M 6.9
a6.9.1 Evaluation of Expression Tree
Ga. cribe expressior tree with an example. Example 1
(4 Marks) Consider a tree as follows
.
A binary expression tree is a specific kind of a binary
.
tree used to represent expressions.

Two common types of expressions that a binary


expression tree can represent are algebraic and

boolean
These trees can represent expressions that contain both Itcan be evaluated as
unary and binary operators.
5*4 2 0
Each node of a binary tree, and hence of a binary
100 - 20 = 80
expression tree, has zero, one, or two children
This restricted structure simplifies the processing of 20+80 100
expression trees.
Result is 100
6. The leaves of binary expression
a tree are operands, Example 2
such as constants or variable names, and the other
Consider another Tree as follows:
nodes contain operators.
7. These particular trees happen to be binary, because all
of the operations are binary, and although this is the
simplest case, it is possible for nodes to have more than
two children.
8. It is also possible for a node to have only one child, as
is the with the unary minus operator.
case

An expression tree, T, can be evaluated by applying the


It can be evaluated as:
operator at the root to the values obtained by
recursively evaluating the left and right sub-trees. 5 *4 20
10. Assume the set of possible operators are (+','", '*, T}. 20/2 1 0
The set of possible operands are [0-19] 100 10= 90
1. See the Fig. 6.9.1, which is the binary expression tree
20+90 = 110
for the expression (in in-fix notation) : (2+3)*9)+7)
Result is 110

GQ. Draw the tree structure for the


following expression
(a- 3b) (2x-y) (4 Marks);
**

a-3 b (2X-Y)f3
Fig. 6.9.1 3 b 2 x-y
(a) (b)

GTU-New abus w.e.f. academic year19-20) (G3-01) Tech-Neo Publications.M.A SACHIN SHAH Venture
Data Structures
(Nonlinear Data Structure)..Page no. (6-44
(GTU-Sem. 3-Comp/lT)

(c)

(d)
(d)
GQ. Draw the tree structure for the following expressions
GO. structure for the following expressions
Draw the tree
2y 3z 4 4a +5b :(2a+5b (-7y (4 Marks)
6c d+4z) (4 Marke)
Stepwise construction of tree

(x +2y +3z-4 - 4a (7d+4z )


+5b +6c)

(a) (2-a+5bts (x-7. y)t4 2*a+5.b


x-7 y
(a) (b)

x+2y+ 3z - 4- 4a
+5b +6c

(b)

2 a 5 b 7

(c)
O
6c 7d

(c) (d)

Ventun
w.e.f. academic year 19-20) (G3-01) Tech-Neo Publications...A SACHI SHAH
(GTU-New Syllabus
aStructures (GTU-Sem. 3-Comp/IT) (NonlinearData Structure)....Page no. (6-45)
Data

GO, Draw the tree


structure for
following expression:
a1a 7b5c)(3a+ 4b+8c (4 Marks)
- -

(11a+7b+50 (3a +4b 8c) Q


(a)

(e)

11a+7b+5c 3a+4b+8c GQ. Draw the tree structure for the following expression
b) (5x+7y)/(3x +5y +3z
(4 Marks)

8c
5x+7y (3x + 5y + 32)

11a 76 3a 4b

O-
(c)

d) 0-0
STU-tNew e.f. academic year 19-20) (G3-01) Tech-Neo Publications .MA SACHIN SHAH Venture
Data Structures (GTU-Sem. 3-Comp/IT (Nonlinear Data Structure)...Page
no. (6-46
UQ. Obtain the expression tree from the following post| a 6.10.1 AVL Tree / Height Balanced Trea
fix representation
ab+cde+**. GTU -S-14, 2 Marks - - - - -

Given expression is : ab+ cde + ** UQ. What is the meaning of height balancerd
tree ? How rebalancing is done in height balan ed
tree? OR Write short note on
: Height Balaneancec
Tree. OR Explain AVL tree with the help of
example
also show insertion and deletion with
the
help of an example. OR Explain AVL tree with
example. OR Explain insert and delete operations
AVLtrees with suitable examples. OR Discuss height
balance tree.

GTU-W-10, W-11, S-14,6 Marks, W-14


W-16, S-19, W-19 (New Syllabus), 3 Marks
-- *-..
Ua. Consider the expression
v1v2-(v3+v4^v5). Show (A) Explanation of AVL Tree
the tree
corresponding to the expression.
1. AVL tree is considered as a self balanced binur
GTU-S-17.3 Marks search tree. The meaning is that AVL tree is
an
also a

binary search tree but it is a balanced tree.


2. A binary tree is
considered as balanced, when the
difference between the heights of left and
righ
sub-trees of every node in the tree is in the range of
-
O or +1.
. In other words,we can say that a
binary tree is said t
be balanced if for every node, height of its children
differ by at most one.
In an AVL tree, every node maintains an extr
LECTURE - 8
information called as balance factor.
Syllabus Covered
The AVL tree was introduced in the
year of 1962 by
Applications ofTree: Some Balanced Tree G.M. Adelson-Velsky and E.M. Landis.
Mechanisms
(i) AVL Tree / Height Balanced Tree (B) Definition of AVL Treee
(i) Operations on AVL Tree An AVL tree is a balanced binary search tree in which
the balance factor of every node is either -1,0 or +1.
Civ) B-Trees
Balance Factor = height of Left Subtree - height ot
6.10 APPLICATIONS OF TREE : SOME Right Subtree
BALANCED TREE MECHANIsMS
. .
Example
ua. Write short note on following: Applications of Trees.
GTU W-11,4 Marks
There are different balanced tree mechanisms such as
AVL Tree / Height Balance Tree, Weight Balanced
Balance factor(20) 38
Tree etc.
10
0
48)
Fig. 6.10.1: AVL Tree

(GTU-New Syllabus w.e.f. academic year 19-20) (G3-01) Tech-Neo Publications ..A SACHIN SHAH V
Structures
TU-Sem. 3-Comp/IT) (Nonlinear Data Structure). Page no. (6-47)2
Data
Fig. 6.10.1
In F
tree is abinary search tree and in this tree Operations on AVL Tree
and ever node satisfies the balance factor -

each
is said to be AVL tree. Ua. Explain insert and delete operations in AVL trees
condition. So this
tree an

Heights of Nodes with suitable examples. GTU S-16, 7 Marks


--- --*
- -

Node Height Algorithm for insertion


insert a new element into the tree using
12 Step 1: First,
BST's (Binary Search Tree) insertion logic.
10 check the
Step 2: After inserting elements you have to
Balance Factor of each node.
22 will be
20 1+max(ht(10).ht(22)) Step 3 When the Balance Factor of every node
will
= 1 +2
found as 0 or 1 or -1 then the algorithm
proceed for next operation.
= 3 node comes
Step 4 When the balance factor of any
values then tree is
28 other than the above three
imbalanced. Then perform the
said to be
30 balanced and then
suitable Rotation to make it
operation.
38 algorithm willproceed for next
48
Algorithm for Deletion
40
k is stored
1+max(ht(30),ht(40)) Step 1: Firstly, find the node where
36 of node
delete those contents
Secondly
= 1 +2=3
Step2 (Suppose the node is x)
1+max(ht(20).ht(36) =

AVL tree can


=1+3=4 Claim Deleting a node in an
Step 3 leaf. There are three
balance factors of nodes be reduced to deleting a
Now we will see

0 possible cases
All leaf nodes has BF as

When x has no children then, delete x


Balance Factor
Node
child, let x' becomes the child
has one
h-
bg When x

have a child, since sub


of x. Notice: x' cannot
12 0 (Leaf Node) most one :
trees of T can differ in height by at
10 0- ht(12) with the
contents of x
=0-1 =-1 then replace the
contents of x'
O(Leaf Node)
22
then delete x' (a leaf)
ht(10) - ht(22)
20 children, then find x's
When x has two
2 - 1 =1 Step 4 left child) then
successor z (which has no
O(Leaf Node)
28 x's contents with z's contents, and
ht(28) - 0
replace
30 delete z
= 1 - 0 =1
you will end up
In all of the three
cases,
OLeaf Node)
38 removing a leaf.
OLeaf Node) the
48 element, if the difference in
After addition of
new

ht(38) - ht(48) sub-trees becomes nmore than 1.


and right
40 height of left
= 1 - I = 0 use rotation techniques to balance it.
then we have to
ht(30) - ht(40)
36
2-2 0

ht(20) - ht(36)
25
Venture
= 3 - 3 =0
Tech-Neo
Publications...A SACHIN SHAH
(G3-01)
19-20)
New Syllabus w.e.f. academic year
Data Structures (GTU-Sem. 3-Comp/lT) (Nonlinear Data Structure)Page no. (6-4p
Insern 3, 2 and 1

AVL Rotations

To balance itself, an AVL tree may perform the

following four kinds of rotations


To make balanced we use After RR Rotatin
1. Left rotation Tree ls RR rotation which moves Tree is Balanced
imbalanced
because node 3 has balarced lactor 2 nodes one position to right
2. Right rotation Fig. 6.10.4: RR Rotation
3. Left-Right rotation
3. Left Right Rotation (LR Rotation)
4 Right-Left rotation The LR Rotation is combination of single left rotation
Left Rotation (LL Rotation) followedby single right rotation. In LR Roration, fint
Single Rotation every node moves one position to left then one positicn
Right Rotation (RR Rotation)
Rotations to right from the current position. To understand LR
Left Right Rotation (LR ROotation) Rotation, let us consider following insertion operations
Double Rotation
Right Left Rotation (RL Rotation) into an AVL Tree.
Insern 3, 1 and 2

Fig.6.10.2: AVL Rotations


After After
LL Rotation RR Rotalo
1. Left Rotation (LL Rotation)

In LL Rotation every node moves one position to left After LR Rotatic


Tree
imbalanced
LL Rolation RR Rotation
Tree is Balanced
from the current position. To understand LL Rotation, DCaUse node 3 has balanced taclor 2

let us consider following insertion operations into an


Fig. 6.10.5: RR Rotation
AVL Tree.
4. Right Left Rotation (RL Rotation)
Insert 1, 2 and 3
The RL Rotation is combination of single right rotation
Q followed by single left rotation. In RL Rotation, first
every node moves one position to right then one
position to left from the current position.
To understand RL Rotation, let us consider following
Tree is imbalanced To make balanced we use After LL Rotation insertion operations into an AVL Tree.
LL Rotation which moves Tree is Balanced Insert 3, 1 and 2
nodes one position to left
After After
LL Rotation RR Rotation
Fig. 6.10.3: LL Rotation

2. Right Rotation (RR Rotation) Tree i LL Rotation AR Rotation Ater LA Rotation

mbalanced Tree is Balancec

Decause node 3has balancedtactor2


In RR Rotation every node moves one position to right
from the current position. To understand RR Rotation, Fig. 6.10.6: RR Rotation
--*

let us consider following insertion operations into an


Ua. Obtain the AVL tree for the following data : MA
AVL Tree.
MAY, NOV, AUG, APR, JAN, DEC, JUN, FEB, JUL, OCT
SEP. Show the balance factor
ofeach node and sho
rotations for the entire process.
GTU-W-14, 7 Marks

(GTU-New Syllabus w.e.f. academic year 19-20) (G3-01)


ATech-Neo Publications...A SACHIN SHAH VE
tures (GTU-Sem. 3-Comp/T)
Data (NonlinearData Structure)...Page no. (6-49)

Insert After insertions


After Balancing
MAR, MAY, NOV

MAR)-2
RR
MAY-1 MAY)0

NOVo MAR)0 NOV)0


AUG, APR

2
MAR NOV MAY*
1

AUG AUG
NOV
APR) (APR (MAR

JAN AN
(MAY+2 MAR
o

AUG
CNOV AUG MAY
+1

(APR MAR) APR JAN NOV


JAN

DEC,JUN,FEB
MAR2 MAR

AUG MAY DEC MAY)


+1
APR) JAN AUG JAN
NOV) NOV
DEC JUN APR FEB JUN

FEB
5. JUL
MAR2 JAN
DEC MAY1

MA DEC+1 MAR)0
AuG JAN VOV CAUu FEBJUN MAY

APR) FEB JUN (APR) JUL NOV

JUL)

New
Syllabus w.e.f. academic year 19-20) (G3-01) Tech-Neo Publications ...A SACHIN SHAH Venture
Data Structures (GTU-Sem. 3-Comp/lT) (Nonlinear Data Structure)...Page no
6-50)
Insert After insertions After Balancing

SEP
JAN JAN

DEC) MAR)1 DEC (MAR)0

AUG FED MAT UG FEBUN" NOv


APR)o NOV APR) (JUL MAY SEP
SEP

6.10.2 B-Trees 6. Property #6: All the key values within a node musthe
in Ascending Order.
n a binary search tree, AVL Tree, etc., every node can
For example, B-Tree of Order 4 contains maximum
have only one value (key) and maximum of two
3 key values in a node and maximum 4 children for a
children but there is another type of search tree called
node.
B-Tree in which a node can store more than one values
(keys) and it can have more than two children.
Example
B-Tree was developed in the year of 1972 by Bayer 30 70
and McCreightwith the name Height Balanced m-way
Search Tree. Later it was named as B-Tree. 26 4050J

Definition of B-Tree
B-Tree can be defined as follows:
********** ************* * *****o
Fig.6.10.7: B-Tree
Ua. Define B-Tree. GTU-S-16, 1 Mark
Operations on B-Tree
B-Tree is a self-balanced search tree with multiple
keys in every node and more than two children for every The following operations are performed on a B-Tree...

node. 1. Search 2. Insertion


Here, number of keys in a node and number of children 3 Deletion
for a node is depend on the order of the B-Tree.
1. Search Operation in B-Tree
Every B-Tree has order.
) In a B-Tree, the search operation is similar to that ef
B-Tree of Order m has the following properties Binary Search Tree.
i) In a Binary search tree, the search process starts from
Ua. Mention the properties ofa B-Tree.
the root node and every time we make a 2-wa
GTU-W-15, 3 Marks
- . . . . . - - - - . . . . - . .
decision (we go to either left subtree or right subtree).
Property #1: All the leaf nodes must be at same level. (ii) In B-Tree also search process starts from the root node
2. Property #2: All nodes except root must have at least but every time we make n-way decision where n is the
m/2-1 keys and maximum of m-1 keys. total number of children that node has. In a B-Tree. the

3. Property #3: All non


leaf nodes except root search operation is performed with O(log n)tume
(i.e. all internal nodes) must have at least m/2 children. complexity.
4. Property #4: lf the root node is a non
leaf node, then
it must have at least 2 children.
leaf node with n-1 keys
5. Property #5: A non must

have n number of children.

academic year 19-20) (G3-01) nture

(GTU-New Syllabus we.f. Tech-Neo Publications..A SACHIN SHAHVen


Data

res (GTU-Sem. 3-Comp/T)


S t r u c t u r e s( G T U - S e n

(Nonlinear Data Structure) ..Page no. (6-51)

The search operation is performed as follows.. (V) As discussed above, to insert a new key, we go down
Read the search element from the user from root to leaf. Before traversing down to a node, we
Slep

Compare. the search element with first key first check if the node is full. If the node is full, we
Step2 value of root node in the tree.
split it to create space.
1f both are matching. then display "Given node
Step3 found!!" and terminate the function.
Algorithm to Insert node in B-Tree
en4: If both are not matching, then check whether
search element is smaller or larger than that key (1) Initialize x as root.
value.
(2) While x is not leaf, do following
If search element is smaller, then continue the
Step5 search process in left subtree. (a) Find the child of x that is going to be traversed
If search element is larger, then compare with next. Let the child be y.
Step6
next key value in the node and repeat step
same (6) Ify is not full, change x to point to y.
3, 4, 5 and 6 until we found exact match or
comparison completed with last key value in a (c) Ify is full, split it and change x to point to one of
leaf node. the two parts of y. If k is smaller than mid key in
Step 7 If we completed with last key value in a leaf y, then set x as first part of y. Else second part of
node, then display "Element not found" and key from y to its
y. When we split y, we move a
terminate the function.
parent x.

2. Insertion Operation in B-Tree (3) The loop in step 2 stops when x is leaf. x must have
space for 1 extra key as we have been splitting all
i) A new key is always inserted at leaf node. Let the key nodes in advance. So simply insert k to x.
to be inserted be k. Like BST, we start from root and
Let us understand the algorithm with an example tree
traverse down till we reach a leaf node.
of minimum degree "t' as 3 and a sequence of integers
(i) Once we reach a leaf node, we insert the key in that
10, 20, 30, 40, 50, 60, 70, 80 and 90 in an initially
leaf node. Unlike BSTs, we have a predefined range on
empty B-Tree.
number of keys that a node can contain. So before
Initially root is NULL. Let us first insert 10.
inserting a key to node, we make sure that the node has
Insert 10
extra space. How to make sure that a node has space
available for key before the key is inserted? We use an
operation called splitChild() that is used to split a child
of a node. See the following diagram to understand Let us now insert 20, 30, 40 and 50. They all will be
split. inserted in root because maximum number of keys a
i) In the following diagram, child y of x is being split into node can accommodate is 2*t- 1 which is 5.
two nodes y and z. Insert 20,30,40 and 50
iv) Note that the splitChild operation moves a key up and
10 20 30 40 50
this is the reason B-Trees grow up unlike BSTs which
grow down. Let us nowinsert 60. Since root node is full, it will first
X
X split into two, then 60 will be inserted into the
50 100 200 Functionality of
splitChild)
50 80 100200 appropriate child.
Insert 60

S570 80 85 90
1 12 T3
10 20 40 50
T4 T5 T6 T1 T2 T3 T4 T5 T6

Fig. 6.10.8 Functionality of Splitting


1020 40 50 60
CTU-Nyllabus
ew we.f. academic year 19-20) (G3-01) Tech-Neo Publications ...A SACHIN SHAH Venture
(Nonlinear Data Structure)..Page no, (t
Data Structures (GTU-Sem. 3-Comp/IT)
will be
Algorithm to delete node from B-Tree
Let us now insert 70 and 80. These new keys
inserted into the appropriate leaf without any split. If the key k is in node x and x is a leaf, delete e
1
Insert 70 and 80 from x.
I fthe key k is in node x and x is an internal no
2.
thefollowing:
10 20 40 50 60 70 80 (a) If the child y that precedes k in node x has at
le
keys, then find the predecessor kO of k in the
3. Deletion Operation in B-Tree
rooted at y. Recursively delete k0, and replace k
) Deletion from a B-tree is more complicated than
in x. (We can find ko and delete it ina
insertion, because we can delete a key from any node-
downward pass.)
not just a leaf-and when we delete a key from an
intermal node, we will have to rearrange the node's (6) If y has fewer than t keys, then, symmetr.
examine the child z that follows k in node x. li zte
children.
least t keys, then find the successor k0 of kr
ii) As in insertion, we must make sure the deletion doesn't
subtree rooted at z. Recursively delete k0, and re
violate the B-tree properties.
k by kO in x. (We can find k0 and delete it in a
(ii) Just as we had to ensure that a node didn't get too big
due to insertion, we must ensure that a node doesn't get
downward pass.)
too small during deletion (except that the root is (c) Otherwise, if bothy and z have only t-1 keys. me-

allowed to have fewer than the minimum number t-l1 and all of z into y, so that x loses both k and the

of keys). to z, and y now contains 2t-1 keys. Then free:


recursively delete k from y.
iv) Just as a simple insertion algorithm might have to back
up if a node on the path to where the key was to be 3. If the key k is not present in internal node x, dete
inserted was full, a simple approach to deletion might the root x.c(i) of the appropriate subtree that
have to back up if a node (other than the root) along contain k, if k is in the tree at all. If x.c(i) has on
the path to where the key is to be deleted has the
keys, execute step 3a or 3b as necessary to guur
minimum number of keys. that we descend to a node containing at least
(v) The deletion procedure deletes the key k from the Then finish by recursing on the appropriate childe
subtree rooted at x.
(a) lf x.c(i) has only t-1 keys but has an immediate si
itself
(vi) This procedure guarantees that whenever it calls with at least t keys, give x.c(i) an extra key by me
node x, the number of keys in x is at
recursively on a
a key from x down into x.ci), moving a key
least the minimum degree t.
x.ci) 's immediate leftor right sibling up into s
(vii) Note that this condition requires one more key than the moving the appropriate child pointer from the s
minimum required by the usual B-tree conditions,
into x.ci).
since sometimes may have to be moved into
a key a

child node before recursion descends to that child.


(b) If x.c(i) and both of x.c(iy's immediate siblings hi
I keys, merge x.ci) with one sibling, which in
delete
(vi) This strengthened condition allows key
us to a
moving a key from x down into the new merge
from the tree in one downward pass without having to
to become the median key for that node.
"back up" (with one exception).
for
The following figures explain the deletion pree
(ix) You should interpret the following specification
deletion from a B-tree with the understanding that if (a) Initial Tree

the root node x ever becomes an internal node having


situation can occur in cases 2c and 3b
no keys (this
then we delete x, and x's only child x.cl becomes the

new root of the tree, decreasing the height of the tree


the property that the root of the
by one and preserving
tree contains at least one key (unless the tree is empty).
SHAH Vem
academic year 19-20) (G3-01) Tech-Neo Publications..A SACHIN
(GTU-New Syllabus w.e.f.
Data Structures(GTU-Sem. 3-Comp/IT) (NonlinearData Structure)...Page
no. (6-53)

(b) F
deleted: case 1
LECTURE-9
Syllabus Covered
c, GM 2-3 Trees

(i) Weight Balanced Tree


(ii) Introduction to Graph
(iv) Graph Terminologies
2a
(c) M deleted: case
a 6.10.3 2-3 Trees

(A) Definition of 2-3 Trees


UQ. Explain the term:2-3tree.
GTU-W-16,- 1 Mark
----

or a single node
A 2-3 Tree is a null tree (zero nodes)
node tree with
the
one node) or a multiple
(d) G deleted: case 2c tree (only
following properties:
three children.
Each interior node has
two or
1
leaf has the same length.
Each path from the root to a
2.

(B) Fields of a Node


1. Internal Node
(e) D deleted: case 3b

PP
P: Pointer to first child.

Pointer to second
child.
Pa:
Pointer to third child.
P:
height Smallest key that is of second child.
descendent
(e') tree shrinks in k:
descendent ofthird
child.
Smallest key that is
k:

2. Leaf Node

key other fields

Each leaf contains a


are placed at the leaves.
Records
record (and key).
case 3a
( B deleted:

E,L,PTX
12

Fig.6.10.9: Trees

Venture
Publications.A SACHIN SHAH
Tech-Neo
lumic vear 19-20) (63-01)
Data Structures (GTU-Sem. 3-Comp/lT) (Nonlinear Data structure) .... Page no
Up till now we have seen various linear data
6-54
(

6.10.4 Welght Balanced Tree 2 data structlure


****

like Stack. Queue and Linked list while one


one nnon-linear
Ga. Write a short note on weight balanced tree datastructure: Tree.
(4 Marks)
Now we are going to learn another
3. non-linear al
***

(A) Definition of weight-balanced tree structure that is Graph.


A weight-balanced binary tree is a binary tree which 4. Graphs are very powerful and versatile data struet
is balanced depending upon the knowledge of the
that easily allow us to represent real life relationsh
probabilities of searching for each individual node. between different types of data (nodes).
In all the sub-trees, the node having highestweight is
present at the root. 5. There are two main parts ofa graph
This leads to more efficient searching performance. 1. The vertices (nodes) where the data is stored

(B) Example of weight balanced tree 2. The edges (connections) which connect the node

In the Fig. 6.10.10 we can observe that the letters (A) Definition of Graph
represent values of nodes while the numbers represent va. With figure, explain the following terms: Graph
weights of nodes.
The tree is ordered using values just like a general
GTU-S-15,S-16, 1Mark
--*°~-**---.

binary search tree. Graph is a collection of set of vertices V where t


The weight can be considered as probability or activity actual data is stored and set of edges E which connects tho
count associated with the node. vertices.

20 The following is a graph with 5 vertices and 6 edges


This graph G can be defined as G = (V. E

Where V {A.B,CD,E} and


1 E (A.B),(A,CYA,D),(B,D).(C.D),(B.E).E.D)
Edge

Vertices

Fig. 6.10.10: Weight Balanced Tree


As the weight of node G is highest, it is root in the tree. Fig.6.11.1:Graph
In the left sub-tree, the A is starting node as it has Nagpur
Nashik
highest weight out of all nodes with values that come

before G.
Similarly, in the right sub-tree, N is the highest-
Mumbai
weighted node that comes after G.
INTRODUCTION TO GRAPH (FOR
6.11
Pune
READING)

1. We know that there are various data structures Fig. 6.11.2: Real life example ofGraph
linear and while
available which are mainly categorized as
In Fig. 6.11.2 the vertices represents the cilues
non-linear data structures. edges represents the road between two cities.
Venture

(GTU-New Syllabus w.e.f. academic year 19-20) (63-01) Tech-Neo Publications...A SACHIN SHAF
tures(GTU-Sem. 3-Comp/T) (Nonlinear Data Structure)..Page no. (6-55)
Dala
Stn

are number of real life examples of graph. To 2 .


There are number Arc (Edge)
of graph exactly, we will see
anderstand the concept
examples (A) Definition of Arc (Edge)
some ofthese
An Edge is the connecting link between two vertices.
1. Representation of road network of cities
also called Arc.
where Edge is as

2 Connecting with friends on social media,


each user is a vertex, and when users connect they ( B ) Explanation of Arc (Edge)
create an edge. 1
An edge is represented as (starting Vertex, ending
to find a
3. Using GPS/Google Maps/Yahoo Maps, Vertex).
route based on shortest route.
2. For example in Fig. 6.1 l.1, the link between vertices A

search for webpages, where pages on and B is represented as (A, B).


4 Google, to
other by (A.D),
the internet are linked to each
3. In this graph, there are
7 edges: (A,B), (A.C),
and the link
each page is (B,D), B.E), (C.D) and (D, E).
a vertex
hyperlinks;
between two pages is an edge.
In Fig. 6.11.1, there are 4 edges:
(Pune, Mumbai),
4.
and (Nasik, Nagpur).
5. On eCommerce websites relationship graphs are
(Pune, Nagpur), (Mumbai, Nasik)
recommendations.
used to show
3. Directed Edge
M6.12 GRAPH TERMINOLOGIES
(A) Definition of Directed Graph
-

with reference to graphs. of a tree. (1 Mark)


UQ. Discuss following GQ. Define directed edge
* * * * * * *
- ---**--****

9 Directed graph which has specific directions, is called as


The edge
) Undirected graph
directed edge.
(i) Degree of vertex
4. Undirected Graph
OR
Define the terms with respect to graph graph with diagram.
GQ. Describe undirected
OR Explain Path, Graph, Cycle (2Marks)
In-degree, Path, Cycle. - --******
terms:
ORDefine the following till now we have seen all the undirected graphs.
of vertex OR Up
Path, Cycle, Degree the edges do not show any directions.
That means
terms
Define the following
) Path
(A) Definition of Undirected Graph
show any
of a vertex The graph in which the edges do not

(i) Indegree and outdegree Undirected Graph.


direction is called as

Gi) Connected graph


GTU-W-09, S-13,W-11, S-12, W-13 (B) Explanation of Undirected Graph
examples of
S-14, S-17, 5Marks 1. Fig. 6.11.1 and Fig.
6.11.2 both are

regarding undirected graph


will see some important terminologies called as
'We not have directions are
2. The edges which do
Graph. undirected edges.
vertices make two
1. Node (Vertex) In undirected graph every
pair of
3.
edges.
(A) Definition of Node vertices Pune and
For example,
in the Fig. 6.11.2
graph is known as4 Mumbai) and
element in a two edges as (Pune,
very individual Mumbai represents considered as
are
ertex. Vertex is also called as a Node. Pune). Both the edges
(Mumbai,
E are vertices.
in
Fig. 6.11.1 -

A, B, C, D & are
same.
and Nagpur
Pune, Mumbai, Nasik
ig. 6.11.1 -

Venture
Publications...A SACHIN SHAH
vertices. Tech-Neo
(63-01)
19-20)
New Syllabus w.e.f. ademic year

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy