128
Tree The data structures that we have learn such as array, linked lists stacks, Queues were linear data structures. As against this trees are non – linear data structures. Tree is a very flexible and powerful data structure that can be used for a wide variety of application. Tree is mainly used to represent data containing a hierarchical relationship between elements. Tree is known as Hierarchical data structure. Tree is a data structure which allows us to associate a parent child relationship between various data elements. Tree is a dynamic data structure. Elements of a Tree in known as nodes. each node has a info and link to another

TreeS

Embed Size (px)

Citation preview

Page 1: TreeS

TreeThe data structures that we have learn such as array, linked lists stacks, Queues were linear data structures. As against this trees are non – linear data structures.

Tree is a very flexible and powerful data structure that can be used for a wide variety of application. Tree is mainly used to represent data containing a hierarchical relationship between elements.

Tree is known as Hierarchical data structure. Tree is a data structure which allows us to associate a parent child relationship between various data elements. Tree is a dynamic data structure. Elements of a Tree in known as nodes. each node has a info and link to another node.

TreeTree

Page 2: TreeS

A

B

ED

C

F

H I

Root Node

Root of Leftsub Tree

Root of Rightsub Tree

Edge

Leaf Node or Leaves OrTerminal Node

Page 3: TreeS

Root Node: A single node in a tree which has no parent node ex:ADegree: The Number of Sub Trees of a node is called its Degree ex: Degree of root node A is 2/degree of node c is one and node f is 2Leaf /Leaves/Terminal Node: A node with degree of Zero or A node which have no child node ex: Node D ,E,H,INon-Terminal Node: A Node which have one or more child node ex: B,C,FSiblings: Children of same parent are called siblings. Ex-B,CAncestor: Ancestor of a node are all the nodes along the path form the root to that node Ex: Ancestor of Node D is B and ADescendant: Descendant of a node are all the nodes along the path form node to terminal node. Ex: descendant of Node A is B and D.Level: Each node in a tree is assigned a level Number. The root node is at level no. 0 and any other node assign a level no one more than its father Ex: A root Node Level ->0 B/C-Level ->1 or F->2Depth or Height: one more than its largest level No. Ex: Depth 4

TermsTerms

Page 4: TreeS

Forest Tree: if we remove the root of a tree we get a forest

Page 5: TreeS

A Tree is Binary tree if each node of it can have at the most two branches. A binary Tree is a finite set of elements that is either empty or is partitioned into three disjoint sub sets. The first sub set contains a single element called the root of the tree. The other two sub sets are themselves binary trees, called the left and right sub trees of the original tree A left or right sub tree can be empty. Each element of a binary tree is called a node of the tree. The tree shown in figure consists of nine nodes with A as its root, its left sub tree is rooted at B and its right sub tree is rooted at C. this is indicated by the two branches emanating from A to B on the left and to C on the right. The absence of a branch indicates an empty sub tree. In Binary Tree there is no node with degree greater than two.

A

B

ED

G

C

F

H I

Binary Tree

Binary TreeBinary Tree

Page 6: TreeS

Strictly Binary Tree: If every non-leaf node in a binary tree has non –empty left and right sub trees the tree is termed a strictly binary tree that is every node have two child. Where as in previous fig one node C and E have only one child.

A

B

D

C

F G

E

Strictly BTreeStrictly BTree

Page 7: TreeS

Complete Binary Tree: A complete binary tree of any depth is a strictly Binary tree that is each node of tree have at most two children and all of whose leaves are at the same level. complete Tree is also known as full Tree.

B C

gGD FE

A

Complete BTreeComplete BTree

Page 8: TreeS

1

2 3

4 765

11 1210

13 14

15

8 9

Q 1 Define the following:1. The Siblings of node 62. The subtree with root 53. The height of node 34. The Depth of node 135. The degree of node 3

Hight |

Page 9: TreeS

A

B

C

E

D

Q2.List the terminal nodes non terminal nodes and the level of each node

Sol:E & D is Terminal NodesA,B,C are Non terminal NodesA->0B->1C->2D->2E->3

Page 10: TreeS

Draw a binary tree using given Expression:E=V+U/X * Y - Z

Sol: ( (V+ ( ( U/X ) * Y ) ) –Z )

U X

/ y

*

+

V

-

z

Page 11: TreeS

BINARY TREE

The Structure of each node of a binary tree contains the data fieldand since a binary tree is recursive in nature it contains the pointerto the same structure.Instead of one pointer it contains two pointerone for the left child and another for the right child Struct tnode{Struct tnode *left;Int data;Struct tnode *right;}Array Representation of Binary trees:-When a binary tree is represented by array three separate arraysare required .One array arr stores the data fields of the trees.The other two arrays lc and rc represents the left child and right childof the nodes.

Page 12: TreeS

A

B C

D E G

H

F

Page 13: TreeS

The array lc and rc contains the index of the array arr where the data is present .if the node does not have any left child or right child then the element of the array lc or rc contains a value –1.The 0th element of the array arr that contains the data is always the root node of the tree.Some elements of the array arr contains’\ 0’which represents an empty child.

AA BB CC DD EE FF GG ‘‘\0’\0’ ‘‘\0’\0’ HH11 33 55 -1-1 99 -1-1 -1-1 -1-1 -1-1 -1-122 44 66 -1-1 -1-1 -1-1 -1-1 -1-1 -1-1 -1-1

ARR

LC

RC

Suppose we want to find the left and right child of the node E. Then we need to find the value present at index 4 in array lc andrc since E is present at index 4 in the array arr.The value present at index 4 in the array lc is 9 which is the index position of node Hso the left child of the node E is H .The right child of the node E isempty because the value present at index 4 in the array rc is -1

Index: 0 1 2 3 4 5 6 7 8 9

Page 14: TreeS

Linked Representation of Binary trees:- Binary trees can be represented by links where each node contains the address of the left child and the right child. The leaf node contains a NULL value in its link fields as there is no child to a leaf node. Some node also have NULL value in its left or right link field because the respective child of that particular node could be empty.

Page 15: TreeS

A

B

F G

C

D EN N N N N N N

NN x

Page 16: TreeS

In -Order

1. Traverse the left sub tree2. Visit the root3. Traverse the right sub tree

In this technique first of all we process the left sub tree T1 of the root node R in the binary tree T.Then process the root R and at last we process the right sub tree T2 of R. We first process the left sub tree terminal node D then root of D that is B and the last the right sub tree of B is E.The left sub tree of E is F that is terminal node.We first process F and then right sub tree of E .There is no right sub tree hence we process E. Thus all the nodes of left sub tree is processed .Secondly we process root R and then process right sub tree T2 in the similar fashion as T1 and resulting list is as follows:D,B,F,E,A,G,C,L,J,M,H,O,K

In orderIn order

L Root R

Traversal of a binary Tree:-

Page 17: TreeS

Algo:step 1: [do through step 4]

if node != NULL Step 2: call inorder(left child [node])Step 3: output info[node] step 4: call inorder(Right child[node])Step 5:exit

Page 18: TreeS

B C

D E G H

L

JF K

MO

A

D,B,F,E,A,G,C,L,J,M,H,O,K

L Root R

Page 19: TreeS

PRE-ORDER:-( root,left,right)

AB C

D E G H

L

JF

PPRREE--OORRDDEERR

K

MO

A , B, D, E, F, C, G, H, J, L, M, K ,O

Page 20: TreeS

Algo: step 1: [do through step 3]

if node != NULL output info[node]Step 2: call preorder(left child [node])Step 3: call preorder(Right child[node])Step 4:exit

PRE-ORDER:-( root, left, right) : in this method each node is visited before its children are visited the root is visited first.

1.Visit the root2.Traverse the left sub tree3.Traverse the right sub tree

Page 21: TreeS

Post -Order

1. Traverse the left sub tree2. Traverse the right sub tree3. Visit the root

In this technique first of all we process the left sub tree T1 of the root node R in the binary tree T.Then the right sub tree T2 and at last the root R The left sub tree of of R is T1 root of T1 is B and its left sub tree is terminal node.We process D first Now we consider right sub tree of B that is E the left sub Tree of E is F so process F at the second Priority.As there is no right sub tree of E we process E and at last root of the sub tree T1, that is B.In the same fashion we process all the nodes of the right sub tree T2.The final list of elements after traversing binary is as follows:D,F,E,B,G,L,M,J,O,K,H,C,A

Post orderPost order

Post Order:-( left, right, root)

Page 22: TreeS

B C

D E G H

L

JF K

MO

A

D,F,E,B,G,L,M,J,O,K,H,C,A

( left, right, root)

Page 23: TreeS

Algo:step 1: [do through step 4]

if node != NULL Step 2: call postorder(left child [node])Step 3: call postorder(Right child[node])step 4: output info[node] Step 5exit

Page 24: TreeS

QQ

* -/ 7 3 1

4 2

+

In-Order: 4/2*7+3-1Pre-Order:+ * / 4 2 7 – 3 1Post Order: 4 2 / 7 * 3 1 - +

In-Order: L Root R

PRE-ORDER:-( root ,left, right) Post Order:-( left, right, root)

Page 25: TreeS

QQ

+ /a - - -

b

*

cd e

+

h

f gIn-Order: a + b – c * d – e / f + g – h Pre-Order: * + a – b c / - d e - + f g hPost Order: a b c - + d e – f g + h - / *

In-Order: L Root R

PRE-ORDER:-( root ,left, right) Post Order:-( left, right, root)

Page 26: TreeS

A Binary Search Tree (BST) is an ordered Binary Tree Such that either it is empty tree or following properties:

1. Each data value in it’s left sub tree is less than the root value2. Each data value in it’s right sub tree is greater than the root

value3. left and right sub tree are again binary tree.A binary tree that has these properties is called a binary search

tree. The advantage to its use is that it provides fast searching.

BINARY SEARCH TREESBinary search TreeBinary search Tree

Page 27: TreeS

Draw binary search tree of the following elements and givethe leaf nodes, non leaf nodes and depth.75,35,89,23,98,75,20,88,30

75

35

23

20

89

9888

20 30

Level 0

Level 1

Level 2

Level 3

Leaf Node- 20,30,88,98Non Leaf Node- 23,35,75,89Depth is 4

qq

Page 28: TreeS

20

17

6

5 8

Draw binary search tree of the following elements and given20,17,6,8,10,7,18,13,12,5

18

10

13

12

7

qq

In-Order:5,6,7,8,10,12,13,17,18,20Pre:20,17,6,5,8,7,10,13,12,18Post:5,7,12,13,10,8,6,18,17,20

Page 29: TreeS

qq

Draw 14,10,17,12,10,11,20,12,18,25,20,8,22,11,23

14

10

8 12

11

17

20

2518

22

23

Page 30: TreeS

#include <stdio.h>#include <conio.h>#include <malloc.h>struct btreenode{ struct btreenode *leftchild ;

int data ;struct btreenode *rightchild ;

} ;void insert ( struct btreenode **, int ) ;void inorder ( struct btreenode * ) ;void preorder ( struct btreenode * ) ;void postorder ( struct btreenode * ) ;void main( ){

struct btreenode *bt ;int req, i = 1, num ;bt = NULL ; /* empty tree */printf ( "Specify the number of items to be inserted: " ) ;

Page 31: TreeS

scanf ( "%d", &req ) ;while ( i <= req ){

printf ( "Enter the data: " ) ;scanf ( "%d", &num ) ;insert ( &bt, num ) ;i++;

}printf ( "\nIn-order Traversal: " ) ;inorder ( bt ) ;printf ( "\nPre-order Traversal: " ) ;preorder ( bt ) ;printf ( "\nPost-order Traversal: " ) ;postorder ( bt ) ;getch( );

}

Page 32: TreeS

void insert ( struct btreenode **sr, int num ){ if ( *sr == NULL )

{*sr = malloc( sizeof ( struct btreenode ) ) ;( *sr ) -> leftchild = NULL ;( *sr ) -> data = num ;( *sr ) -> rightchild = NULL ;return ;

}else /* search the node to which new node will be attached */{ /* if new data is less, traverse to left */

if ( num < ( *sr ) -> data )insert ( &( ( *sr ) -> leftchild ), num ) ;

else/* else traverse to right */

insert ( &( ( *sr ) -> rightchild ), num ) ;}

}

Page 33: TreeS

void inorder ( struct btreenode *sr ){

if ( sr != NULL ){

inorder ( sr -> leftchild ) ;printf ( "\t%d", sr -> data ) ;inorder ( sr -> rightchild ) ;

}}

Page 34: TreeS

void preorder ( struct btreenode *sr ){

if ( sr != NULL ){

printf ( "\t%d", sr -> data ) ;preorder ( sr -> leftchild ) ;preorder ( sr -> rightchild ) ;

}}

Page 35: TreeS

void postorder ( struct btreenode *sr ){

if ( sr != NULL ){

postorder ( sr -> leftchild ) ;postorder ( sr -> rightchild ) ;printf ( "\t%d", sr -> data ) ;

}}

Page 36: TreeS

20

17

6

17

8

Input: 20,17,6,8

Output:

In-Order: 6,8,17,20 Pre: 20,17,6,8Post: 6,8,17,20

Page 37: TreeS

Operations on a Binary Search TreeInserting of a node in bst

To insert any node into a BST,initially the data that is to be inserted is compared with the data of the root node.if the data is found to greater than or equal to the data of the root node then the new node is inserted in the right sub-tree of the root node,otherwise the new node is inserted in the left sub tree of the root node.Now the root node of the right or left sub tree is taken and its data is compared with the data that is to be inserted and the same procedure is repeated.Ex- Suppose the new node that is to be inserted holds a value 7 in its data field.to find the appropriate position of this new node in the tree,it is compared with the root node which holds a value 20 since 7 is less than 20 the searching of appropriate position of new node will be done in the left sub tree. Next 7 is compared with 6 and since 7 is greater than 6 the searching of appropriate position of new node is done in the right sub tree of the node that holds a value 6 now 7 is compared with 8 and since 7 is less than 8 the searching of appropriate positon of the new node is done in the left sub tree. But since this left sub tree is empty the new node is made the left child of the node that holds a value 8

Inserting a node in bstInserting a node in bst

Page 38: TreeS

2017 23

6 18

5 8

10

9

25

24 29

BST before Insertion

Page 39: TreeS

2017 23

6 18

5 8

10

9

25

24 29

BST After Insertion

7

Page 40: TreeS

Algo:INSBST(INFO,LEFT,RIGHT,ROOT,AVAIL,ITEM,LOC)1. Call FIND(INFO,LEFT,RIGHT,ROOT,ITEM,LOC,PAR)2. If LOC != NULL then Exit3. [ Copy the ITEM into new node in AVAIL list]

a) if AVIL = NULL then write: OVERFLOW and Exitb) set NEW= AVIL , AVIL = LEFT[AVIL] and INFO[NEW]=ITEMc) Set LOC=NEW, LEFT[NEW]=NULL and RIGHT[NEW]=NULL

4. [ add ITEM to tree]if PAR=NULL THEN Set ROOT=NEWelse if ITEM<INFO[PAR] THEN Set LEFT[PAR]=NEWelse Set RIGHT[PAR]=NEW

5. Exit

Page 41: TreeS

Deletion a node from BST

To delete a node into BST there are four case that we need to consider:

Case (a) No Node in the tree contains the specified dataIn this case we print the message that the data item is not present in the tree.

Case (b) The node containing the data has no children

In this case node to be deleted has no children the memory occupied by this should be freed and either the left link or the right link of the parent of this node should be set to NULL. Which of these to set to NULL depends upon whether the node being deleted is a left child or a right child of its parent.Case (c) The node containing the data has exactly one childIn this case node to be deleted has one child. So we have to adjust the pointer of the parent of the node to be deleted such that after deletion it points to the child of the node being deleted.

Deletion a node form BstDeletion a node form Bst

Page 42: TreeS

2017 23

6 18

5 8

10

9

25

24 29

Before deletion

Page 43: TreeS

2017 23

6 18

10

25

24 29

After Deletion

9

case C

5

Page 44: TreeS

Case (d) The node containing the data has two childrenIn this case node to be deleted has two children. So the solution is more complex. Consider node 8 shown in fig before deletion. The inorder successor of the node 8 is node 9 the data of this in order successor should now be copied into the node to be deleted and a pointer should be set up pointing to the in – order successor (node 9).This in order successor would always have one or zero child. This in order successor should then be deleted using the same procedure as for deleting a one child or a zero child node. Thus the whole logic of deleting a node with two children is to locate the in order successor,copy its data and reduce the problem to simple deletion of a node with one or zero child.

Page 45: TreeS

2017 23

6 18

5 8

10

9

25

24 29

Before deletion

7

Page 46: TreeS

2017 23

6 18

5 9

10

25

24 29

After Deletion

case D

7

Page 47: TreeS

Algo:

Delete_node(info,parent,loc)Step 1: call search_node(info,parent,loc)Step 2: if loc=NULL

output “Information does exists in the tree” and Exitelse if left_child[loc]!=NULL and

right_child[loc]!=NULL call Delete_node(parent,loc)call Dele(parent,loc)

Search Algo

Case C :Delete_node AlgoDelete_node(parent,loc)step 1: ( i ) Temp=Right_child[Loc]

(i i) Parent_succ=LocStep 2: Repeat while Left_child[Temp]!=NULL

case D

Page 48: TreeS

( i ) parent_succ=Temp(ii) Temp=Left_child[Temp](iii) Successor=parent(iv) parent_Successor= save

Step 3: call Dele(Temp,parent_succ)Step 4: (i) if parent!= NULL then

if Loc = Left_child[Parent] thenLeft_child[parent]=Tempelse Left_child[Temp]=Left_child[Loc]Right_child[Successor]=Right_child[Loc]

Step 4: Return

Dele AlgoDele(Loc,Parent)Step 1: [Initialization]

if Left_child[Loc]=NULL thenDnode=Right_child[Loc]Else Dnode=Left_child[Loc]

Page 49: TreeS

Step 2: if Parent !=NULL thenif Loc=Left_child[Parent]then Left_child[Parent]=DnodeElse Right_child[Parent]=DnodeElse Root=Dnode

Step 3: Return

Page 50: TreeS

Search a node form BSTTo search any node in a binary Tree the data that is to be searched is compared with the data of the root node.if the data is equal to the data of the root node then the searching is successful.If the data is found to be greater than the data of the root node then the searching process proceeds in the right sub tree of the root node ,otherwise Searching process proceeds in the left sub tree of the root node. Same procedure is repeated for the left or right sub tree until the data is found Ex- Suppose the data that is to be searched is 8 initially 8 is compared with root node which holds a value 20 and since 8 is less than 20 the searching would proceed in the left sub tree. Now 8 is compared 17 and since 8 is less than 17 the searching would proceed in the left sub tree of the node which holds a value 17 .Next 8 is compared with 6 and since 8 is greater than 6 the searching proceeds in the right sub tree of the node which holds a value 6 .now 8 is compared with the node which holds a value 8 and since 8 is found the searching process ends here.

Search a node from BstSearch a node from Bst

Page 51: TreeS

2017

6 18

5 8

107

Page 52: TreeS

AlgAlgooSearch_node(node,info)Step 1: [initialize]

Flag=0Step 2: Repeat Through step 3 while node!= NULLStep 3: if info[node]=info

flag=1return(flag)else if info<info[node]node=Left_child[node]else node=Right_child[node]

Step 4: Return(flag)

Page 53: TreeS

119

8 10

7

13

1412

Input:

15

In Order: 7 ,8,9,10,11,12,13,14,15after del: 7,8,9,11,12,13,14,15

Page 54: TreeS

#include <stdio.h>#include <conio.h>#include <alloc.h>#define TRUE 1#define FALSE 0struct btreenode{ struct btreenode *leftchild ;

int data ;struct btreenode *rightchild ;

} ;void insert ( struct btreenode **, int ) ;void delete ( struct btreenode **, int ) ;void search ( struct btreenode **, int, struct btreenode **,struct btreenode **, int * ) ;void inorder ( struct btreenode * ) ;void main( ){struct btreenode *bt ;

int req, i = 0, num, a[ ] = { 11, 9, 13, 8, 10, 12, 14, 15, 7 } ;

Page 55: TreeS

bt = NULL ; /* empty tree */while ( i <= 8 )

{insert ( &bt, a[i] ) ;i++ ;

} printf ( "Binary tree before deletion:\n" ) ;inorder ( bt ) ;delete ( &bt, 10 ) ;printf ( "\nBinary tree after deletion:\n" ) ;inorder ( bt ) ;delete ( &bt, 14 ) ;printf ( "\nBinary tree after deletion:\n" ) ;inorder ( bt ) ;delete ( &bt, 13 ) ;

printf ( "\nBinary tree after deletion:\n" ) ;inorder ( bt ) ;getch( );

}

Page 56: TreeS

void insert ( struct btreenode **sr, int num ){

if ( *sr == NULL ){*sr = malloc ( sizeof ( struct btreenode ) ) ;

( *sr ) -> leftchild = NULL ;( *sr ) -> data = num ;( *sr ) -> rightchild = NULL ;

}else { if ( num < ( *sr ) -> data )

insert ( &( ( *sr ) -> leftchild ), num ) ;

Page 57: TreeS

elseinsert ( &( ( *sr ) -> rightchild ), num ) ;

}}void delete ( struct btreenode **root, int num ){

int found ;struct btreenode *parent, *x, *xsucc ;/* if tree is empty */if ( *root == NULL ){

printf ( "\nTree is empty" ) ;return ;

}parent = x = NULL ;

Page 58: TreeS

search ( root, num, &parent, &x, &found ) ;/* if the node to deleted is not found */if ( found == FALSE ){

printf ( "\nData to be deleted, not found" ) ;return ;

}/* if the node to be deleted has two children */if ( x -> leftchild != NULL && x -> rightchild != NULL ){

parent = x ;xsucc = x -> rightchild ;while ( xsucc -> leftchild != NULL ){

parent = xsucc ;xsucc = xsucc -> leftchild ;}

Page 59: TreeS

x -> data = xsucc -> data ;x = xsucc ;

}/* if the node to be deleted has no child */if ( x -> leftchild == NULL && x -> rightchild == NULL ){

if ( parent -> rightchild == x )parent -> rightchild = NULL ;

elseparent -> leftchild = NULL ;free ( x ) ;

return ;}/* if the node to be deleted has only rightchild */if ( x -> leftchild == NULL && x -> rightchild != NULL ){

if ( parent -> leftchild == x )parent -> leftchild = x -> rightchild ;

Page 60: TreeS

elseparent -> rightchild = x -> rightchild ;free ( x ) ;

return ;}/* if the node to be deleted has only left child */if ( x -> leftchild != NULL && x -> rightchild == NULL ){

if ( parent -> leftchild == x )parent -> leftchild = x -> leftchild ;

elseparent -> rightchild = x -> leftchild ;

free ( x ) ;return ;

}}

Page 61: TreeS

void search ( struct btreenode **root, int num, struct btreenode **par, struct btreenode **x, int *found ){

struct btreenode *q ;q = *root ;*found = FALSE ;*par = NULL ;while ( q != NULL ){

/* if the node to be deleted is found */if ( q -> data == num ){

*found = TRUE ;*x = q ;return ;

}

Page 62: TreeS

*par = q ;if ( q -> data > num )

q = q -> leftchild ;else

q = q -> rightchild ;}

}void inorder ( struct btreenode *sr ){

if ( sr != NULL ){

inorder ( sr -> leftchild ) ; printf ( "%d\t", sr -> data ) ;

inorder ( sr -> rightchild ) ;}

}

Page 63: TreeS

AVL TREESearching in a binary search tree is efficient if the heights of bothleft and right sub-trees of any node are equal.However,frequent insertion and deletions in a BST is likely to make it unbalanced.The efficiency of searching is ideal if the difference between theheights of left and right sub trees of all the nodes in a binary search tree is at the most one.such a binary search tree is called as BALANCED BINARY TREE.It was invented in the year 1962 by two Russian mathematicians-G.M.Adelson-velskii and E.M. Landis.Hence such tree are also known as AVL tree.To represent a node of an AVL tree four fields are required-one for data,two for storing the address of the left and right child and an additional field is required to hold the balance factor.The balance factor of any node is calculated by subtracting the height of the right sub-tree of the node form the height of the left sub tree.The structure of a node of an AVL tree is given below:

Page 64: TreeS

Struct AVL{Struct AVL *left;Int data;Struct AVL *right;Int balfact;};The value of balfact of any node is –1,0 or 1.if it is other than these

three values then the tree is not balanced or it is not an AVL tree.1. If the value of balfact of any node is –1 then the height of the

right sub-tree of that node is one more than the height of its leftsub-tree.

2. If the value of balfact of any node is 0 then the height of its left and right sub-tree is exactly same.

3. If the value of balfact of any node is 1 then the height of the left sub-tree of that node is one more than the height of its right sub-tree.

4. ( balfact = left – right )

Page 65: TreeS

A

B

D

C

-1

10

0 A

B C

2

0-1

1E

Ex IEx II

D

F0

AVL TREE

NOT A AVL TREE

0

Page 66: TreeS

Insertion of Node in AVL Tree

We can Insert a new node in an AVL tree by finding its appropriate position. But insertion of a new node involves cretain overheads since the tree may become unbalanced due to the increase in its height.If the new node is inserted as a child of any non-leaf node then there will be no effect on its balance, as the height of the tree does not increase.

20

17

0

00

025

23

1860

-1

Before Addition

Page 67: TreeS

17

0

0

0

0

25

23

1860

0

after Addition

20

210

Addition of a new node to the leaf node of a sub tree make it unbalance then to re-balance and make it an AVL tree the nodes need to be properly adjusted. So after insertion of a new node the tree is traversed starting from the new node to the node whose balance factor is disturbed. The nodes are adjusted in such a way that the resultant tree becomes a balanced tree.

Page 68: TreeS

20

6 295 12

10 15

13 32

27Before Addition

0

1

0

0

-1

-10

0 0

0

20

6 295 12

10 15

13 32

27after Addition

1

0

0

-1

-20

0 1

-1

130

1

Page 69: TreeS

As seen form fig. on insertion of the new node the balance factor of the node containing the data 6 violates the condition of an AVL tree. To re-balance the tree we are required to make a left rotation makes the node containing the data 6 as the left child of the node containing the data 12 and the node containing the data 10 as a right child of the node containing the data 6.

LEFT ROTATION

20

12 296 15

1013

26 32

27after Rotation

1

0

0

-1

00

00

1

0

50

Case A:

Page 70: TreeS

20

6 295 12

10 15

13 32

27Before Addition

0

1

0

0

-1

-10

0 0

0

Now suppose instead of 13 we insert a node with value 11. this new node would get inserted as the right child of the node containing a value 10. After this the tree no longer remains a balanced tree.

Case B:

Page 71: TreeS

20

6 295 12

10 15

13 32

27 after Addition

0

1

0

0

-1

-20

-1 0

1

110

To re-balance the tree we are required to make initially a right rotation of the tree along the node 12. Right rotation makes node 10 the right child of node 6 node 12 becomes the right child of node 10 and node 11 becomes the left child of node 12.

Right ROTATION

Page 72: TreeS

20

6 295 10

15

12

13 32

27 after first Rotation

1

1

0

0

-1

-20

0

-2

11 00

But now the tree is not balanced and hence the tree is rotated to left along with node 6. As a result node 10 becomes the left child of the node 20. The node 6 becomes the left child of the node 10. since there is no left child for node 10 the right child of node 6 is empty. Thus finally the tree becomes a balanced binary tree of AVL Tree. this process first to right and then to the left rotation is known as Double Rotation.

double ROTATION

Page 73: TreeS

20

10 296

5

15

1213 32

27

1

0

0

-1

01

00

110 0

0

after second Rotation

Page 74: TreeS

Q1. Draw a AVL Tree 50,45,80,95,26,43,105

50

45 80

95

1

0 0

01

0

-1

260

0

1

430

-1

2Critical Node

Balance 50

43 80

9526 45

0

-1

0

0

0 0

Page 75: TreeS

Balance

50

43 80

9526 45

-2

-1

0

0 0

-1

1050

Critical Node

50

43 95

8026 45

00

0 0

0

1050

0

Page 76: TreeS

Q2. Draw a AVL Tree 25,45,50,55,60,65,75

step 1: 25 step 2: 25

4525

45

step 3:

50

critical node Balance45

25 50

step 4:45

25 50

55

step 5:45

25 50

55

60

critical node

Page 77: TreeS

Balance:

45

25 55

50 60

step 6:45

25 55

50 60

65

Balance:

55

45 60

50 65

critical node

25

Page 78: TreeS

step 7:

55

45 60

50 6525

75

55

45 65

50 6025 75

Balance:

critical node

Page 79: TreeS

Q2. Draw a AVL Tree 5,2,7,0,3,4,6,1,8,9

step 1: 5 step 2: 5

2step 3: 5

2 75

2 7

step 4:

0

step 5: 5

2 7

03

Page 80: TreeS

step 6: 5

2 7

03

4

critical node Balance: 3

2 5

0 4 7

3

2 5

0 4 7

step 7:

6

Page 81: TreeS

3

2 5

0 4 7

step 8:

61

critical3

1 5

0 4 7

Balance:

6

2

3

1 5

0 4 7

6

2

step 9:

8

Page 82: TreeS

3

1 5

0 4 7

6

2

step 10:

8

9

critical node

critical node

3

1 7

0 5 8

6

2

balance

94

Page 83: TreeS

Q 3 Draw AVL Tree 23,75,64,86,43,58,15,26

64

43 75

23 86

26

58

balance

15

23

75

640

1

-2 64

7523 00

0

Page 84: TreeS

64

7523

860

-1-1

64

7523

860

-10

430

-1

64

7523

860

-1

431

2

1

580

64

7543

860

-1

58

0

00

23

0

Page 85: TreeS

64

7543

860

-1

58

1

10

23

1

150

26

64

7543

860

-1

58

1

0 023

1

150 0

Page 86: TreeS

#include <stdio.h>#include <conio.h>#include <malloc.h>#define FALSE 0#define TRUE 1struct AVLNode{

int data ;int balfact ;struct AVLNode *left ;struct AVLNode *right ;

} ;struct AVLNode * buildtree ( struct AVLNode *, int, int * ) ;struct AVLNode * deldata ( struct AVLNode *, int, int * ) ;struct AVLNode * del ( struct AVLNode *, struct AVLNode *,int*) ;struct AVLNode * balright ( struct AVLNode *, int * ) ;struct AVLNode * balleft ( struct AVLNode *, int * ) ;void display ( struct AVLNode * ) ;void deltree ( struct AVLNode * ) ;

Page 87: TreeS

void main( ){

struct AVLNode *avl = NULL ;int h ;clrscr( ) ;avl = buildtree ( avl, 20, &h ) ;avl = buildtree ( avl, 6, &h ) ;avl = buildtree ( avl, 29, &h ) ;avl = buildtree ( avl, 5, &h ) ;printf ( "\nAVL tree:\n" ) ;display ( avl ) ;avl = deldata ( avl, 20, &h ) ;avl = deldata ( avl, 29, &h ) ;printf ( "\nAVL tree after deletion of a node:\n" ) ;display ( avl ) ;deltree ( avl ) ;getch( ) ;

}

Page 88: TreeS

/* inserts an element into tree */struct AVLNode * buildtree (struct AVLNode *root,int data, int *h ){

struct AVLNode *node1, *node2 ;if ( !root ){

root = ( struct AVLNode * ) malloc ( sizeof ( struct AVLNode ) ) ;root -> data = data ;root -> left = NULL ;root -> right = NULL ;root -> balfact = 0 ;*h = TRUE ;return ( root ) ;

}

Page 89: TreeS

if ( data < root -> data ){

root -> left = buildtree ( root -> left, data, h ) ;/* If left subtree is higher */if ( *h ){

switch ( root -> balfact ){

case 1:node1 = root -> left ;if ( node1 -> balfact == 1 ){

printf ( "\nRight rotation along %d.", root -> data ) ;root -> left = node1 -> right ;

node1 -> right = root ;root -> balfact = 0 ;root = node1 ;

}

Page 90: TreeS

else{

printf ( "\nDouble rotation, left along %d", node1 -> data ) ;node2 = node1 -> right ;node1 -> right = node2 -> left

printf ( " then right along %d.\n", root -> data ) ;node2 -> left = node1 ;root -> left = node2 -> right ;node2 -> right = root ;

if ( node2 -> balfact == 1 )root -> balfact = -1 ;

elseroot -> balfact = 0 ;

if ( node2 -> balfact == -1 )node1 -> balfact = 1 ;

elsenode1 -> balfact = 0 ;root = node2 ;

Page 91: TreeS

}root -> balfact = 0 ;

*h = FALSE ;break ;

case 0:root -> balfact = 1 ;break ;

case -1:root -> balfact = 0 ;*h = FALSE ;

}}

}

Page 92: TreeS

if ( data > root -> data ){

root -> right = buildtree ( root -> right, data, h ) ;/* If the right subtree is higher */if ( *h ){switch ( root -> balfact )

{case 1:

root -> balfact = 0 ;*h = FALSE ;break ;

case 0:root -> balfact = -1 ;break;

case -1:node1 = root -> right ;

Page 93: TreeS

if ( node1 -> balfact == -1 ){

printf ( "\nLeft rotation along %d.", root -> data ) ;root -> right = node1 -> left ;

node1 -> left = root ;root -> balfact = 0 ;root = node1 ;}else{

printf ( "\nDouble rotation, right along %d",node1 -> data ) ;node2 = node1 -> left ;

node1 -> left = node2 -> right ;node2 -> right = node1 ;

printf ( " then left along %d.\n", root -> data ) ;root -> right = node2 -> left ;

node2 -> left = root ;

Page 94: TreeS

if ( node2 -> balfact == -1 )root -> balfact = 1 ;

elseroot -> balfact = 0 ;

if ( node2 -> balfact == 1 )node1 -> balfact = -1 ;elsenode1 -> balfact = 0 ;root = node2 ;

}root -> balfact = 0 ;*h = FALSE ;

}}

}return ( root ) ;

}

Page 95: TreeS

/* deletes an item from the tree */struct AVLNode * deldata ( struct AVLNode *root, int data, int *h ){

struct AVLNode *node ;

if ( !root ){

printf ( "\nNo such data." ) ;return ( root ) ;

}else{

if ( data < root -> data ){

root -> left = deldata ( root -> left, data, h ) ;if ( *h )

root = balright ( root, h ) ;}

Page 96: TreeS

else{

if ( data > root -> data ){root -> right = deldata ( root -> right, data, h ) ;

if ( *h )root = balleft ( root, h ) ;

}else{

node = root ;if ( node -> right == NULL ){

root = node -> left ;*h = TRUE ;free ( node ) ;

}

Page 97: TreeS

else {if ( node -> left == NULL )

{ root = node -> right ;*h = TRUE ;free ( node ) ;

}else{

node -> right = del ( node -> right, node, h ) ;if ( *h )root = balleft ( root, h ) ;}

}}

}}return ( root ) ;

}

Page 98: TreeS

struct AVLNode * del ( struct AVLNode *succ, struct AVLNode*node, int *h ){

struct AVLNode *temp = succ ;if ( succ -> left != NULL ){

succ -> left = del ( succ -> left, node, h ) ;if ( *h )

succ = balright ( succ, h ) ;}else{ temp = succ ;

node -> data = succ -> data ;succ = succ -> right ;free ( temp ) ;*h = TRUE ;

}return ( succ ) ;

}

Page 99: TreeS

/* balances the tree, if right sub-tree is higher */struct AVLNode * balright ( struct AVLNode *root, int *h ){

struct AVLNode *node1, *node2 ;switch ( root -> balfact ){

case 1:root -> balfact = 0 ;break;

case 0:root -> balfact = -1 ;*h = FALSE ;break;

case -1:node1 = root -> right ;

Page 100: TreeS

printf ( "\nLeft rotation along %d.", root -> data ) ;root -> right = node1 -> left ;

node1 -> left = root ;if ( node1 -> balfact == 0 ){ root -> balfact = -1 ;

node1 -> balfact = 1 ; *h = FALSE ;}else{root -> balfact = node1 -> balfact = 0 ;}root = node1 ;

}else{

printf ( "\nDouble rotation, right along %d", node1 -> data );

Page 101: TreeS

/* balances the tree, if left sub-tree is higher */struct AVLNode * balleft ( struct AVLNode *root, int *h ){

struct AVLNode *node1, *node2 ;switch ( root -> balfact ){

case -1:root -> balfact = 0 ;break ;

case 0:root -> balfact = 1 ;*h = FALSE ;break ;

case 1:node1 = root -> left ;if ( node1 -> balfact >= 0 ){

printf ( "\nRight rotation along %d.", root -> data ) ;

Page 102: TreeS

root -> left = node1 -> right ;node1 -> right = root ;if ( node1 -> balfact == 0 ){

root -> balfact = 1 ;node1 -> balfact = -1 ;*h = FALSE ;

}else{root -> balfact = node1 -> balfact = 0 ;}root = node1 ;

}else{

Page 103: TreeS

printf ( "\nDouble rotation, left along %d", node1 -> data ) ;node2 = node1 -> right ;node1 -> right = node2 -> left ;node2 -> left = node1 ;

printf ( " then right along %d.\n", root -> data ) ;root -> left = node2 -> right ;node2 -> right = root ;if ( node2 -> balfact == 1 )

root -> balfact = -1 ;else

root -> balfact = 0 ;if ( node2-> balfact == -1 )

node1 -> balfact = 1 ;else

node1 -> balfact = 0 ;root = node2 ;node2 -> balfact = 0 ;

}}return ( root ) ;

}

Page 104: TreeS

if ( node1 -> balfact <= 0 ){

node2 = node1 -> left ;node1 -> left = node2 -> right ;node2 -> right = node1 ;

printf ( " then left along %d.\n", root -> data );root -> right = node2 -> left ;node2 -> left = root ;

if ( node2 -> balfact == -1 )root -> balfact = 1 ;

elseroot -> balfact = 0 ;

if ( node2 -> balfact == 1 )node1 -> balfact = -1 ;

elsenode1 -> balfact = 0 ;

Page 105: TreeS

root = node2 ;node2 -> balfact = 0 ;

}}return ( root ) ;

}

/* displays the tree in-order */void display ( struct AVLNode *root ){

if ( root != NULL ){

display ( root -> left ) ;printf ( "%d\t", root -> data ) ;display ( root -> right ) ;

}}

Page 106: TreeS

/* deletes the tree */void deltree ( struct AVLNode *root ){

if ( root != NULL ){

deltree ( root -> left ) ;deltree ( root -> right ) ;

}free ( root ) ;

}

Page 107: TreeS

Algo Insert In AVLAlgo Insert In AVLNote: That Nodes are inserted into an AVL tree is the same manner as an ordinary binary search Tree. However the insertion algo for an AVL tree Travels back along the path it took to find the point of insertion and checks the balance at each node on the path. If a node is found that is unbalanced if it has a balance factor of either -2 and +2 then rotation is performed based on the inserted nodes position relative to the node being examined.

Page 108: TreeS

Algo Delete Node in AVLAlgo Delete Node in AVLStep 1: P has balance factor and it is equal :than it is changed according to left or right sub tree so it’s value is FALSEStep 2: P has balance factor not equal and taller sub tree was short: than change balance factor p equal and leave it shorter value TRUE.Step 3: P has balance factor not equal and short subtree was also short: apply rotation follows to restore the balance factor let be the root of taller subtree of p. we have 3 cases:Case 3 a: balance factor of q is equal : A single rotation restores the balance and shorter balance became FALSE

Page 109: TreeS

Case 3 b: Balance factor of q is same as that of p: Apply single rotation ,set balance factor p and q to equal and leave shorter as TRUE.Case 3 C: Balance Factor of p and Q are opposite.Step 4: Apply Double rotation set balance factor of new root to equal and other balance factor as appropriate and leave shorter as TRUE.

Page 110: TreeS

B-TreeB-TreeB-TreeThe number of values that a particular node of a binary search

tree or an AVL tree can hold is only one. On the other hand a 2-3 tree can hold only 2 value per node. To improve the efficiency of operation performed on a tree we need to reduce the height of a tree and if a node contains more number of values then at a time more values can be accessed from the memory. To improve the efficiency of tree operations Multi-way search trees can be used. B-Tre is a Multi-way search tree of order n that satisfies the following conditions:

1. All the non-leaf nodes( except the root node ) have at least n/2 children and at the most n children.

2. The non-leaf root node may have at the most n non-empty child and at least two child nodes.

3. A B-Tree can exist with only one node. i.e. the root node containing no child.

Page 111: TreeS

4. All the values of a particular node are in increasing order.5. All the values that appear on the left most child of a root node

are smaller that the first value of root node and All the values that appear on the right most child of a node are greater that the last value of that root node.

6. all the leaf nodes should appear on the same level.7. B-Tree of order n is a tree in which any node may maximum n-

1 values and maximum of n children.

23 39

3 17 31 43 65

B-Tree Of order 3

Page 112: TreeS

23 39

3 17 31 43 65

B-Tree Of order 3In a B Tree of order 4 any node can contain maximum three values and 4 children.

27 42

2,13, 22 32,40 47, 51

B-Tree Of order 4

Page 113: TreeS

Suppose a value k is to be inserted in a B-Tree of order 4. here the maximum number of values that any node may have is 3. After searching for the appropriate leaf node to insert the value k the values present at that particular leaf node is searched. This leads to two possibilities:

Case A:The leaf node is not full (does not contain 3 values): if the leaf node is not full then the value is inserted at its appropriate position and the process end.

Ex: Suppose we want to insert a value 37 to following B-Tree. So first we have to search the node where to insert this value. In our case it is the leaf node that contains the values 32 and 40. Since the node have only two values the third value can be added and hence the insertion process ends here. The value 37 is inserted between 72 & 40 because

27 42

2,13, 22 32,40 47, 51

Insertion in B-TreeInsertion in B-Tree

Page 114: TreeS

The value of any node of a B-Tree always appear in ascending order.

27 42

2,13, 22 32,37,40 47, 51

Case B: The leaf node is full (contains 3 values) :If the leaf node is full , then that node is split into two nodes . 1. If n is n is the order of the tree then any node is always split after the value n/2-1 i.e. 4/2-1 = 1.2. As a result the first part of the node contains the first n/2-1 values i.e. 4/2-1 = 1 values. And n/2 i.e. 4/2=2 children.3. The second part of the node contains the last n-n/2 value i.e. 4-4/2= 2 and n-n/2 +1 child i.e. 4-4/2+1 = 3 children4. The n/2th value i.e. 4/2th = 2nd value is moved up to the parent node and the new value is attached to one of the two split nodes. 5. If the parent node is full then same process is repeated.

Page 115: TreeS

27 42

2,13, 22 32,37,40 47, 51

Ex:

Suppose the value that is to be inserted is 19 . To begin with the node in which 19 can be inserted is searched. In our case it is the node which contains values 2,13, 22 . Since this node already contains three values no more values can be added to this node. Hence as per condition the node is split after the value 4/2-1=1 using this condition we split the node in two parts. First part hold only n/2-1=1 value in our case that is 2 and second part hold last n-n/2 that is 4-4/2=2 value in our case that is 19 and 22 and the value 13 is moved up to the parent node or new value 19 is attached to second node because it is greater than 13.

Page 116: TreeS

13 27 42

232,37,40 47, 5119, 22

Addition of new value in B-Tree of order 4

Q Draw a B-Tree of order 3 2,4,9,8,7,6,3,1,5,10

sol: we know that maximum no of value in one node is n-1 so 3-1=2

Page 117: TreeS

2step 1

2 4step 2

step 3 : Here Overflow problem is arise so node split in two parts

2 4 9

2 9

4

step 4 :

2 8 9

4

Page 118: TreeS

step 5 :

2 8 9

4

Overflow problem node split in two parts

7

2 9

4 8

7

step 6:

2 9

4 8

6 7

Page 119: TreeS

Overflow problem IN NODE

2 3 9

4 8

6 7

step 7:

step 8:

2 3 9

4 8

6 71

4 8

Overflow problem IN parent

2

Page 120: TreeS

1 96 7

4

2 8

3

step 9

1 96 7

4

2 8

3

5Overflow problem

1 95 7

4

2 6 8

3

Page 121: TreeS

1 9 105 7

4

2 6 8

3

step 10

Page 122: TreeS

Deletion In B-TreeDeletion In B-Tree

3 7 97 9983 92

53

14 32 79 96

19 27 37 42 59 64 71

A B-Tree with Order 5To Delete a value first of all its node is searched the valued is deleted and the number of remaining values in the node is counted. After count the value there are two possibilities :Case A: The Number of values is greater than or equal to the minimum number of values required (i.e. 2) for a b-tree of order 5. suppose we want to delete the value 64 on deleting this value the number of values that are left in the node are 2, which satisfy the condition of a B-Tree . Hence the deletion process ends hear.

Page 123: TreeS

3 7 97 9983 92

53

14 32 79 96

19 27 37 42 59 71

A B-Tree After Deletion

Page 124: TreeS

Case B: The number of values is less than the minimum number of values required (i.e. 2) for order 5. Here again there are two possibilities Case (a): The left or right sibling of the node form which the value is deleted contains more than the required minimum number of values. So the value of its (node form which the value is deleted ) parent is moved to the node and a value from its sibling ( Left or Right which contains more number of values than the required minimum values is moved to its parent.

3 7 97 9983 92

53

14 32 79 96

19 27 37 42 59 71

Suppose We want to delete 92

Page 125: TreeS

After deleting the value 92, value 79 is moved form its parent to the node form where the value is deleted. Then the value 71 is moved form its left sibling to its parent the deletion process ends here as all the nodes satisfy the condition of B-Tree.

3 7 97 9979 83

53

14 32 71 96

19 27 37 42 59 64

A B-Tree After Deletion

Page 126: TreeS

Case (b): The left or right sibling of the node form which the value is deleted contains exactly the required minimum number of values. Here the value of its ( node form which the value is deleted ) parent is moved to the node and the node is merged with its sibling. If the parent also contains the minimum number of values then the same procedure of merging the node with its sibling is applied. Suppose we want to delete the value 42.

3 7 79 83

53

14 32 71 96

19 27 37 42 59 64 97 99

Page 127: TreeS

3 7 79 83

53

14 71 96

19 27 32 37 59 64 97 99

After Deletion of the value 42 the node want to delete the value 42. After deletion of the value 42 the node contains only one value 37. So value 32 is copied form its parent and it is merged with its left sibling that contains values 19 and 27. As a result the node now contains 4 values 19,27,32,37. Now the parent node contains only one value 14 . So the value 53 is copied form its parent and is merged with its right sibling that contains value 71 and 96. As a result , the node now contains 4 values 14, 53, 71 and 96. the deletion process ends here as all the nodes satisfy the condition of B-Tree.

Page 128: TreeS

3 7 79 83

14 53 71 96

19 27 32 37 59 64 97 99