55
W Linked L o Linked L o A node next noo The last Uses of L o The list linked to o list size o Empty n o We can Why use List List can be deficontains two fie de in the memo node of the lis Linked Lis is not required ogether to mak is limited to th node can not be store values of linked lis ned as collectio elds i.e. data st ory. st contains poin st to be contiguo ke a list. This ac e memory size e present in the f primitive type st over arr on of objects ca tored at that pa nter to the null. ously present in chieves optimiz and doesn't ne e linked list. s or objects in ray? alled nodes tha articular addres n the memory. zed utilization o eed to be decla the singly linke at are randomly ss and the poin The node can r of space. red in advance ed list. y stored in the ter which conta reside any whee. memory. ains the addres re in the memo ss of the ory and

Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

  • Upload
    others

  • View
    83

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

L

U

W

Linked Lo Linked L

o A node cnext nod

o The last

Uses of Lo The list

linked to

o list size

o Empty n

o We can

Why use

List List can be defin

contains two fiede in the memo

node of the lis

Linked Lisis not required ogether to mak

is limited to th

node can not be

store values of

linked lis

ned as collectio

elds i.e. data story.

st contains poin

st to be contiguo

ke a list. This ac

e memory size

e present in the

f primitive type

st over arr

on of objects ca

tored at that pa

nter to the null.

ously present inchieves optimiz

and doesn't ne

e linked list.

s or objects in

ray?

alled nodes tha

articular addres

n the memory. Tzed utilization o

eed to be decla

the singly linke

at are randomly

ss and the poin

The node can rof space.

red in advance

ed list.

y stored in the

ter which conta

reside any wher

e.

memory.

ains the addres

re in the memo

ss of the

ory and

Page 2: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Till now, we were using array data structure to organize the group of elements that are to be stored individually in the memory. However, Array has several advantages and disadvantages which must be known in order to decide the data structure which will be used throughout the program.

Array contains following limitations:

1. The size of array must be known in advance before using it in the program.

2. Increasing size of the array is a time taking process. It is almost impossible to expand the size of the array at run time.

3. All the elements in the array need to be contiguously stored in the memory. Inserting any element in the array needs shifting of all its predecessors.

Linked list is the data structure which can overcome all the limitations of an array. Using linked list is useful because,

1. It allocates the memory dynamically. All the nodes of linked list are non-contiguously stored in the memory and linked together with the help of pointers.

2. Sizing is no longer a problem since we do not need to define its size at the time of declaration. List grows as per the program's demand and limited to the available memory space.

Singly linked list or One way chain Singly linked list can be defined as the collection of ordered set of elements. The number of elements may vary according to need of the program. A node in the singly linked list consist of two parts: data part and link part. Data part of the node stores actual information that is to be represented by the node while the link part of the node stores the address of its immediate successor.

One way chain or singly linked list can be traversed only in one direction. In other words, we can say that each node contains only next pointer, therefore we can not traverse the list in the reverse direction.

Consider an example where the marks obtained by the student in three subjects are stored in a linked list as shown in the figure.

Page 3: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Itn

OT

N

1. s2. {3. 4. 5. }6. s7. p

I

Ti

In the above figthe different sunode. We can h

OperationThere are vario

Node Crea

struct node { int data; struct node *

}; struct node *heptr = (struct no

Insertion

The insertion innserted, the in

gure, the arrowubject. The last have as many e

ns on Sinous operations w

ation

*next;

ead, *ptr; ode *)malloc(si

nto a singly linksertion is categ

w represents thenode in the lis

elements we req

ngly Linkewhich can be p

zeof(struct nod

ked list can be pgorized into the

e links. The datt is identified bquire, in the da

ed List erformed on sin

de *));

performed at de following cate

ta part of everyby the null pointata part of the l

ngly linked list.

ifferent positionegories.

y node containster which is prelist.

. A list of all suc

ns. Based on th

s the marks obtesent in the add

ch operations is

he position of th

tained by the sdress part of th

s given below.

he new node be

tudent in he last

eing

Page 4: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

SN Operation Description

1 Insertion at

beginning

It involves inserting any element at the front of the list. We just need to a few link

adjustments to make the new node as the head of the list.

2 Insertion at end

of the list

It involves insertion at the last of the linked list. The new node can be inserted as the only

node in the list or it can be inserted as the last one. Different logics are implemented in each

scenario.

3 Insertion after

specified node

It involves insertion after the specified node of the linked list. We need to skip the desired

number of nodes in order to reach the node after which the new node will be inserted. .

Deletion and Traversing

The Deletion of a node from a singly linked list can be performed at different positions. Based on the position of the node being deleted, the operation is categorized into the following categories.

SN Operation Description

1 Deletion at

beginning

It involves deletion of a node from the beginning of the list. This is the simplest operation

among all. It just need a few adjustments in the node pointers.

2 Deletion at the

end of the list

It involves deleting the last node of the list. The list can either be empty or full. Different

logic is implemented for the different scenarios.

3 Deletion after

specified node

It involves deleting the node after the specified node in the list. we need to skip the desired

number of nodes to reach the node after which the node will be deleted. This requires

Page 5: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

traversing through the list.

4 Traversing In traversing, we simply visit each node of the list at least once in order to perform some

specific operation on it, for example, printing data part of each node present in the list.

5 Searching In searching, we match each element of the list with the given element. If the element is

found on any of the location then location of that element is returned otherwise null is

returned. .

Linked List in C: Menu Driven Program

#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node *head; void beginsert (); void lastinsert (); void randominsert(); void begin_delete(); void last_delete(); void random_delete(); void display(); void search();

Page 6: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

void main () { int choice =0; while(choice != 9) { printf("\n\n*********Main Menu*********\n"); printf("\nChoose one option from the following list ...\n"); printf("\n===============================================\n"); printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from Beginning\n 5.Delete from last\n6.Delete node after specified location\n7.Search for an element\n8.Show\n9.Exit\n"); printf("\nEnter your choice?\n"); scanf("\n%d",&choice); switch(choice) { case 1: beginsert(); break; case 2: lastinsert(); break; case 3: randominsert(); break; case 4: begin_delete(); break; case 5: last_delete(); break;

Page 7: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

case 6: random_delete(); break; case 7: search(); break; case 8: display(); break; case 9: exit(0); break; default: printf("Please enter valid choice.."); } } } void beginsert() { struct node *ptr; int item; ptr = (struct node *) malloc(sizeof(struct node *)); if(ptr == NULL) { printf("\nOVERFLOW"); } else { printf("\nEnter value\n");

Page 8: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

scanf("%d",&item); ptr->data = item; ptr->next = head; head = ptr; printf("\nNode inserted"); } } void lastinsert() { struct node *ptr,*temp; int item; ptr = (struct node*)malloc(sizeof(struct node)); if(ptr == NULL) { printf("\nOVERFLOW"); } else { printf("\nEnter value?\n"); scanf("%d",&item); ptr->data = item; if(head == NULL) { ptr -> next = NULL; head = ptr; printf("\nNode inserted"); } else

Page 9: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

{ temp = head; while (temp -> next != NULL) { temp = temp -> next; } temp->next = ptr; ptr->next = NULL; printf("\nNode inserted"); } } } void randominsert() { int i,loc,item; struct node *ptr, *temp; ptr = (struct node *) malloc (sizeof(struct node)); if(ptr == NULL) { printf("\nOVERFLOW"); } else { printf("\nEnter element value"); scanf("%d",&item); ptr->data = item; printf("\nEnter the location after which you want to insert "); scanf("\n%d",&loc);

Page 10: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

temp=head; for(i=0;i<loc;i++) { temp = temp->next; if(temp == NULL) { printf("\ncan't insert\n"); return; } } ptr ->next = temp ->next; temp ->next = ptr; printf("\nNode inserted"); } } void begin_delete() { struct node *ptr; if(head == NULL) { printf("\nList is empty\n"); } else { ptr = head; head = ptr->next; free(ptr); printf("\nNode deleted from the begining ...\n");

Page 11: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

} } void last_delete() { struct node *ptr,*ptr1; if(head == NULL) { printf("\nlist is empty"); } else if(head -> next == NULL) { head = NULL; free(head); printf("\nOnly node of the list deleted ...\n"); } else { ptr = head; while(ptr->next != NULL) { ptr1 = ptr; ptr = ptr ->next; } ptr1->next = NULL; free(ptr); printf("\nDeleted Node from the last ...\n"); } }

Page 12: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

void random_delete() { struct node *ptr,*ptr1; int loc,i; printf("\n Enter the location of the node after which you want to perform deletion \n"); scanf("%d",&loc); ptr=head; for(i=0;i<loc;i++) { ptr1 = ptr; ptr = ptr->next; if(ptr == NULL) { printf("\nCan't delete"); return; } } ptr1 ->next = ptr ->next; free(ptr); printf("\nDeleted node %d ",loc+1); } void search() { struct node *ptr; int item,i=0,flag; ptr = head; if(ptr == NULL) {

Page 13: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

printf("\nEmpty List\n"); } else { printf("\nEnter item which you want to search?\n"); scanf("%d",&item); while (ptr!=NULL) { if(ptr->data == item) { printf("item found at location %d ",i+1); flag=0; } else { flag=1; } i++; ptr = ptr -> next; } if(flag==1) { printf("Item not found\n"); } } } void display()

Page 14: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

{ struct node *ptr; ptr = head; if(ptr == NULL) { printf("Nothing to print"); } else { printf("\nprinting values . . . . .\n"); while (ptr!=NULL) { printf("\n%d",ptr->data); ptr = ptr -> next; } } }

Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence. Therefore, in a doubly linked list, a node consists of three parts: node data, pointer to the next node in sequence (next pointer) , pointer to the previous node (previous pointer). A sample node in a doubly linked list is shown in the figure.

Page 15: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

A doubly linked list containing three nodes having numbers from 1 to 3 in their data part, is shown in the following image.

In C, structure of a node in doubly linked list can be given as :

1. struct node 2. {

Page 16: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

3. struct node *prev; 4. int data; 5. struct node *next; 6. }

The prev part of the first node and the next part of the last node will always contain null indicating end in each direction.

In a singly linked list, we could traverse only in one direction, because each node contains address of the next node and it doesn't have any record of its previous nodes. However, doubly linked list overcome this limitation of singly linked list. Due to the fact that, each node of the list contains the address of its previous node, we can find all the details about the previous node as well by using the previous address stored inside the previous part of each node.

Memory Representation of a doubly linked list Memory Representation of a doubly linked list is shown in the following image. Generally, doubly linked list consumes more space for every node and therefore, causes more expansive basic operations such as insertion and deletion. However, we can easily manipulate the elements of the list since the list maintains pointers in both the directions (forward and backward).

In the following image, the first element of the list that is i.e. 13 stored at address 1. The head pointer points to the starting address 1. Since this is the first element being added to the list therefore the prev of the list contains null. The next node of the list resides at address 4 therefore the first node contains 4 in its next pointer.

We can traverse the list in this way until we find any node containing null or -1 in its next part.

Page 17: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Operations on doubly linked list Node Creation

Page 18: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

1. struct node 2. { 3. struct node *prev; 4. int data; 5. struct node *next; 6. }; 7. struct node *head;

All the remaining operations regarding doubly linked list are described in the following table.

SN Operation Description

1 Insertion at beginning Adding the node into the linked list at beginning.

2 Insertion at end Adding the node into the linked list to the end.

3 Insertion after specified

node

Adding the node into the linked list after the specified node.

4 Deletion at beginning Removing the node from beginning of the list

5 Deletion at the end Removing the node from end of the list.

6 Deletion of the node

having given data

Removing the node which is present just after the node containing the given data.

7 Searching Comparing each node data with the item to be searched and return the location of

the item in the list if the item found else return null.

Page 19: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

8 Traversing Visiting each node of the list at least once in order to perform some specific

operation like searching, sorting, display, etc.

Menu Driven Program in C to implement all the operations of doubly linked list

#include<stdio.h> #include<stdlib.h> struct node { struct node *prev; struct node *next; int data; }; struct node *head; void insertion_beginning(); void insertion_last(); void insertion_specified(); void deletion_beginning(); void deletion_last(); void deletion_specified(); void display(); void search(); void main () { int choice =0; while(choice != 9) { printf("\n*********Main Menu*********\n");

Page 20: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

printf("\nChoose one option from the following list ...\n"); printf("\n===============================================\n"); printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from Beginning\n 5.Delete from last\n6.Delete the node after the given data\n7.Search\n8.Show\n9.Exit\n"); printf("\nEnter your choice?\n"); scanf("\n%d",&choice); switch(choice) { case 1: insertion_beginning(); break; case 2: insertion_last(); break; case 3: insertion_specified(); break; case 4: deletion_beginning(); break; case 5: deletion_last(); break; case 6: deletion_specified(); break; case 7: search(); break;

Page 21: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

case 8: display(); break; case 9: exit(0); break; default: printf("Please enter valid choice.."); } } } void insertion_beginning() { struct node *ptr; int item; ptr = (struct node *)malloc(sizeof(struct node)); if(ptr == NULL) { printf("\nOVERFLOW"); } else { printf("\nEnter Item value"); scanf("%d",&item); if(head==NULL) { ptr->next = NULL; ptr->prev=NULL;

Page 22: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

ptr->data=item; head=ptr; } else { ptr->data=item; ptr->prev=NULL; ptr->next = head; head->prev=ptr; head=ptr; } printf("\nNode inserted\n"); } } void insertion_last() { struct node *ptr,*temp; int item; ptr = (struct node *) malloc(sizeof(struct node)); if(ptr == NULL) { printf("\nOVERFLOW"); } else { printf("\nEnter value"); scanf("%d",&item); ptr->data=item;

Page 23: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

if(head == NULL) { ptr->next = NULL; ptr->prev = NULL; head = ptr; } else { temp = head; while(temp->next!=NULL) { temp = temp->next; } temp->next = ptr; ptr ->prev=temp; ptr->next = NULL; } } printf("\nnode inserted\n"); } void insertion_specified() { struct node *ptr,*temp; int item,loc,i; ptr = (struct node *)malloc(sizeof(struct node)); if(ptr == NULL) { printf("\n OVERFLOW");

Page 24: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

} else { temp=head; printf("Enter the location"); scanf("%d",&loc); for(i=0;i<loc;i++) { temp = temp->next; if(temp == NULL) { printf("\n There are less than %d elements", loc); return; } } printf("Enter value"); scanf("%d",&item); ptr->data = item; ptr->next = temp->next; ptr -> prev = temp; temp->next = ptr; temp->next->prev=ptr; printf("\nnode inserted\n"); } } void deletion_beginning() { struct node *ptr; if(head == NULL)

Page 25: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

{ printf("\n UNDERFLOW"); } else if(head->next == NULL) { head = NULL; free(head); printf("\nnode deleted\n"); } else { ptr = head; head = head -> next; head -> prev = NULL; free(ptr); printf("\nnode deleted\n"); } } void deletion_last() { struct node *ptr; if(head == NULL) { printf("\n UNDERFLOW"); } else if(head->next == NULL) { head = NULL;

Page 26: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

free(head); printf("\nnode deleted\n"); } else { ptr = head; if(ptr->next != NULL) { ptr = ptr -> next; } ptr -> prev -> next = NULL; free(ptr); printf("\nnode deleted\n"); } } void deletion_specified() { struct node *ptr, *temp; int val; printf("\n Enter the data after which the node is to be deleted : "); scanf("%d", &val); ptr = head; while(ptr -> data != val) ptr = ptr -> next; if(ptr -> next == NULL) { printf("\nCan't delete\n"); } else if(ptr -> next -> next == NULL)

Page 27: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

{ ptr ->next = NULL; } else { temp = ptr -> next; ptr -> next = temp -> next; temp -> next -> prev = ptr; free(temp); printf("\nnode deleted\n"); } } void display() { struct node *ptr; printf("\n printing values...\n"); ptr = head; while(ptr != NULL) { printf("%d\n",ptr->data); ptr=ptr->next; } } void search() { struct node *ptr; int item,i=0,flag; ptr = head; if(ptr == NULL)

Page 28: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

{ printf("\nEmpty List\n"); } else { printf("\nEnter item which you want to search?\n"); scanf("%d",&item); while (ptr!=NULL) { if(ptr->data == item) { printf("\nitem found at location %d ",i+1); flag=0; break; } else { flag=1; } i++; ptr = ptr -> next; } if(flag==1) { printf("\nItem not found\n"); } } 1. }

Page 29: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Tree o A Tree is a recursive data structure containing the set of one or more data nodes where one node is designated as the

root of the tree while the remaining nodes are called as the children of the root.

o The nodes other than the root node are partitioned into the non empty sets where each one of them is to be called sub-tree.

o Nodes of a tree either maintain a parent-child relationship between them or they are sister nodes.

o In a general tree, A node can have any number of children nodes but it can have only a single parent.

o The following image shows a tree, where the node A is the root node of the tree while the other nodes can be seen as the children of A.

Page 30: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Basic terminology o Root Node :- The root node is the topmost node in the tree hierarchy. In other words, the root node is the one which

doesn't have any parent.

o Sub Tree :- If the root node is not null, the tree T1, T2 and T3 is called sub-trees of the root node.

Page 31: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

o Leaf Node :- The node of tree, which doesn't have any child node, is called leaf node. Leaf node is the bottom most node of the tree. There can be any number of leaf nodes present in a general tree. Leaf nodes can also be called external nodes.

o Path :- The sequence of consecutive edges is called path. In the tree shown in the above image, path to the node E is A→ B → E.

o Ancestor node :- An ancestor of a node is any predecessor node on a path from root to that node. The root node doesn't have any ancestors. In the tree shown in the above image, the node F have the ancestors, B and A.

o Degree :- Degree of a node is equal to number of children, a node have. In the tree shown in the above image, the degree of node B is 2. Degree of a leaf node is always 0 while in a complete binary tree, degree of each node is equal to 2.

o Level Number :- Each node of the tree is assigned a level number in such a way that each node is present at one level higher than its parent. Root node of the tree is always present at level 0.

Static representation of tree 1. #define MAXNODE 500 2. struct treenode { 3. int root; 4. int father; 5. int son; 6. int next; 7. }

Dynamic representation of tree 1. struct treenode 2. { 3. int root;

Page 32: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

4. struct treenode *father; 5. struct treenode *son 6. struct treenode *next; 7. }

Types of Tree The tree data structure can be classified into six different categories.

General Tree

General Tree stores the elements in a hierarchical order in which the top level element is always present at level 0 as the root element. All the nodes except the root node are present at number of levels. The nodes which are present on the same level

Page 33: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

are called siblings while the nodes which are present on the different levels exhibit the parent-child relationship among them. A node may contain any number of sub-trees. The tree in which each node contain 3 sub-tree, is called ternary tree.

Forests

Forest can be defined as the set of disjoint trees which can be obtained by deleting the root node and the edges which connects root node to the first level node.

Page 34: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Binary Tree

Binary tree is a data structure in which each node can have at most 2 children. The node present at the top most level is called the root node. A node with the 0 children is called leaf node. Binary Trees are used in the applications like expression evaluation and many more. We will discuss binary tree in detail, later in this tutorial.

Binary Search Tree

Binary search tree is an ordered binary tree. All the elements in the left sub-tree are less than the root while elements present in the right sub-tree are greater than or equal to the root node element. Binary search trees are used in most of the applications of computer science domain like searching, sorting, etc.

Expression Tree

Expression trees are used to evaluate the simple arithmetic expressions. Expression tree is basically a binary tree where internal nodes are represented by operators while the leaf nodes are represented by operands. Expression trees are widely used to solve algebraic expressions like (a+b)*(a-b). Consider the following example.

Q. Construct an expression tree by using the following algebraic expression.

(a + b) / (a*b - c) + d

Page 35: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Tournament Tree

Tournament tree are used to record the winner of the match in each round being played between two players. Tournament tree can also be called as selection tree or winner tree. External nodes represent the players among which a match is being played while the internal nodes represent the winner of the match played. At the top most level, the winner of the tournament is present as the root node of the tree.

For example, tree .of a chess tournament being played among 4 players is shown as follows. However, the winner in the left sub-tree will play against the winner of right sub-tree.

Page 36: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

 

 

 

 

 

Binary Tree Binary Tree is a special type of generic tree in which, each node can have at most two children. Binary tree is generally partitioned into three disjoint subsets.

1. Root of the node

2. left sub-tree which is also a binary tree.

3. Right binary sub-tree

A binary Tree is shown in the following image.

Page 37: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Types of Binary Tree

1. Strictly Binary Tree

In Strictly Binary Tree, every non-leaf node contain non-empty left and right sub-trees. In other words, the degree of every non-leaf node will always be 2. A strictly binary tree with n leaves, will have (2n - 1) nodes.

A strictly binary tree is shown in the following figure.

Page 38: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

2. Complete Binary Tree

A Binary Tree is said to be a complete binary tree if all of the leaves are located at the same level d. A complete binary tree is a binary tree that contains exactly 2^l nodes at each level between level 0 and d. The total number of nodes in a complete binary tree with depth d is 2d+1-1 where leaf nodes are 2d while non-leaf nodes are 2d-1.

Page 39: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Binary Tree Traversal

SN  Traversal  Description

1 Pre-order

Traversal

Traverse the root first then traverse into the left sub-tree and right sub-tree respectively. This

procedure will be applied to each sub-tree of the tree recursively.

2 In-order

Traversal

Traverse the left sub-tree first, and then traverse the root and the right sub-tree respectively.

This procedure will be applied to each sub-tree of the tree recursively.

3 Post-order

Traversal

Traverse the left sub-tree and then traverse the right sub-tree and root respectively. This

procedure will be applied to each sub-tree of the tree recursively.

Page 40: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Binary Tree representation There are two types of representation of a binary tree:

1. Linked Representation

In this representation, the binary tree is stored in the memory, in the form of a linked list where the number of nodes are stored at non-contiguous memory locations and linked together by inheriting parent child relationship like a tree. every node contains three parts : pointer to the left node, data element and pointer to the right node. Each binary tree has a root pointer which points to the root node of the binary tree. In an empty binary tree, the root pointer will point to null.

Consider the binary tree given in the figure below.

Page 41: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

In the above figure, a tree is seen as the collection of nodes where each node contains three parts : left pointer, data element and right pointer. Left pointer stores the address of the left child while the right pointer stores the address of the right child. The leaf node contains null in its left and right pointers.

The following image shows about how the memory will be allocated for the binary tree by using linked representation. There is a special pointer maintained in the memory which points to the root node of the tree. Every node in the tree contains the address of its left and right child. Leaf node contains null in its left and right pointers.

Page 42: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

2. Sequential Representation

This is the simplest memory allocation technique to store the tree elements but it is an inefficient technique since it requires a lot of space to store the tree elements. A binary tree is shown in the following figure along with its memory allocation.

Page 43: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

In this representation, an array is used to store the tree elements. Size of the array will be equal to the number of nodes present in the tree. The root node of the tree will be present at the 1st index of the array. If a node is stored at ith index then its left and right children will be stored at 2i and 2i+1 location. If the 1st index of the array i.e. tree[1] is 0, it means that the tree is empty.

 

 

Binary Search Tree 1. Binary Search tree can be defined as a class of binary trees, in which the nodes are arranged in a specific order. This is

also called ordered binary tree.

2. In a binary search tree, the value of all the nodes in the left sub-tree is less than the value of the root.

3. Similarly, value of all the nodes in the right sub-tree is greater than or equal to the value of the root.

4. This rule will be recursively applied to all the left and right sub-trees of the root.

Page 44: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

A Binary search tree is shown in the above figure. As the constraint applied on the BST, we can see that the root node 30 doesn't contain any value greater than or equal to 30 in its left sub-tree and it also doesn't contain any value less than 30 in its right sub-tree.

Advantages of using binary search tree 1. Searching become very efficient in a binary search tree since, we get a hint at each step, about which sub-tree contains

the desired element.

Page 45: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

2. The binary search tree is considered as efficient data structure in compare to arrays and linked lists. In searching process, it removes half sub-tree at every step. Searching for an element in a binary search tree takes o(log2n) time. In worst case, the time it takes to search an element is 0(n).

3. It also speed up the insertion and deletion operations as compare to that in array and linked list.

Q. Create the binary search tree using the following data elements.

43, 10, 79, 90, 12, 54, 11, 9, 50

1. Insert 43 into the tree as the root of the tree.

2. Read the next element, if it is lesser than the root node element, insert it as the root of the left sub-tree.

3. Otherwise, insert it as the root of the right of the right sub-tree.

The process of creating BST by using the given elements, is shown in the image below.

Page 46: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence
Page 47: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Operations on Binary Search Tree There are many operations which can be performed on a binary search tree.

SN  Operation  Description

1 Searching in

BST

Finding the location of some specific element in a binary search tree.

2 Insertion in

BST

Adding a new element to the binary search tree at the appropriate location so that the property

of BST do not violate.

3 Deletion in

BST

Deleting some specific node from a binary search tree. However, there can be various cases in

deletion depending upon the number of children, the node have.

Program to implement BST operations #include <iostream> #include <stdlib.h> using namespace std; struct Node { int data; Node *left; Node *right; };

Page 48: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Node* create(int item) { Node* node = new Node; node->data = item; node->left = node->right = NULL; return node; } void inorder(Node *root) { if (root == NULL) return; inorder(root->left); cout<< root->data << " "; inorder(root->right); } Node* findMinimum(Node* cur) { while(cur->left != NULL) { cur = cur->left; } return cur; } Node* insertion(Node* root, int item) { if (root == NULL) return create(item); if (item < root->data)

Page 49: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

root->left = insertion(root->left, item); else root->right = insertion(root->right, item); return root; } void search(Node* &cur, int item, Node* &parent) { while (cur != NULL && cur->data != item) { parent = cur; if (item < cur->data) cur = cur->left; else cur = cur->right; } } void deletion(Node*& root, int item) { Node* parent = NULL; Node* cur = root; search(cur, item, parent); if (cur == NULL) return;

Page 50: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

if (cur->left == NULL && cur->right == NULL) { if (cur != root) { if (parent->left == cur) parent->left = NULL; else parent->right = NULL; } else root = NULL; free(cur); } else if (cur->left && cur->right) { Node* succ = findMinimum(cur- >right); int val = succ->data; deletion(root, succ->data); cur->data = val; } else { Node* child = (cur->left)? Cur- >left: cur->right;

Page 51: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

if (cur != root) { if (cur == parent->left) parent->left = child; else parent->right = child; } else root = child; free(cur); } } int main() { Node* root = NULL; int keys[8]; for(int i=0;i<8;i++) { cout << "Enter value to be inserted"; cin>>keys[i]; root = insertion(root, keys[i]); } inorder(root); cout<<"\n"; deletion(root, 10); inorder(root);

Page 52: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

return 0; }

 

AVL Tree AVL Tree is invented by GM Adelson - Velsky and EM Landis in 1962. The tree is named AVL in honour of its inventors.

AVL Tree can be defined as height balanced binary search tree in which each node is associated with a balance factor which is calculated by subtracting the height of its right sub-tree from that of its left sub-tree.

Tree is said to be balanced if balance factor of each node is in between -1 to 1, otherwise, the tree will be unbalanced and need to be balanced.

Balance Factor (k) = height (left(k)) - height (right(k)) If balance factor of any node is 1, it means that the left sub-tree is one level higher than the right sub-tree.

If balance factor of any node is 0, it means that the left sub-tree and right sub-tree contain equal height.

If balance factor of any node is -1, it means that the left sub-tree is one level lower than the right sub-tree.

An AVL tree is given in the following figure. We can see that, balance factor associated with each node is in between -1 and +1. therefore, it is an example of AVL tree.

Page 53: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Complexity

Algorithm  Average case Worst case

Space o(n) o(n)

Page 54: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

Search o(log n) o(log n)

Insert o(log n) o(log n)

Delete o(log n) o(log n)

Operations on AVL tree Due to the fact that, AVL tree is also a binary search tree therefore, all the operations are performed in the same way as they are performed in a binary search tree. Searching and traversing do not lead to the violation in property of AVL tree. However, insertion and deletion are the operations which can violate this property and therefore, they need to be revisited.

SN  Operation  Description 

1 Insertion Insertion in AVL tree is performed in the same way as it is performed in a binary search tree.

However, it may lead to violation in the AVL tree property and therefore the tree may need balancing.

The tree can be balanced by applying rotations.

2 Deletion Deletion can also be performed in the same way as it is performed in a binary search tree. Deletion

may also disturb the balance of the tree therefore, various types of rotations are used to rebalance

the tree.

Why AVL Tree ?

Page 55: Linked List · Doubly linked list Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence

AVL tree controls the height of the binary search tree by not letting it to be skewed. The time taken for all operations in a binary search tree of height h is O(h). However, it can be extended to O(n) if the BST becomes skewed (i.e. worst case). By limiting this height to log n, AVL tree imposes an upper bound on each operation to be O(log n) where n is the number of nodes.