Vous êtes sur la page 1sur 90

DEPARTMENT OF COMPUTER SCINCE & ENGINEERING

ADVANCED DATA STRUCTURES & ALGORITHMS LAB

Prepar By Mr. T.Bhaskar Asst Prof (cse dept)

SREE CHAITANYA INSTITUTE OF TECHNOLOGY & SCIENCES


( Affiliated to JNTU,Hyd. & Approved by AICTE New Delhi) LMD COLONY, THIMMAPOOR KARIM NAGAR PIN: 505527.

Department of CSE

ADSA Lab Manual

Contents 1) Write C++ program to implement the following using an array a) Stack ADT b) Queue ADT 2) Write C++ programs to implement the following using a singly linked list a) Stack ADT b) Queue ADT 3) Write C++ program to implement the dequeue (double ended queue) ADT using a doubly linked list 4) Write a C++ program to perform the following operations: a) Insert element into a binary search tree. b) Delete an element from a binary search tree c) Search for a key element in a binary search tree 5) Write a C++ program to implement circular queue ADT using an array 6) Write a C++ programs that use non-recursive functions to traverse the given binary tree in a) Preorder b) in order c) post order 7) Write a C++ programs for the implementation of bfs and dfs for a given graph 8) Write C++ programs for implementing that following sorting methods: a) Quick sort b) Merge sort c) Heap sort 9) Write a C++ program to perform the following operations a) Insertion into a B-tree b) Deletion from B-tree 10) Write a C++ program to perform the following operations a) Insertion into an AVL tree b) Deletion from an AVL tree 11) Write a C++ program to implement kruskals algorithm to generate a minimum spanning tree 12) Write a C++ program for implement prims algorithm to generate a minimum spanning tree 13) Write a C++ program to implement all the functions of a dictionary (ADT) using hashing

SCITS, KNR

Department of CSE

ADSA Lab Manual

TABLE OF CONTENTS

S.N

TITLE (List of programs)

PAGE NO

1 2 3 4 5 6 7 8 9 10 11 12 13 14

a) Stack ADT b) Queue ADT using an array a) Stack ADT b) Queue ADT using SLL Dequeue ADT using a doubly linked list Insert Delete Search operations in binary search Circular queue ADT using an array a) Preorder b) in order c) post order BFS and DFS for a given graph a) Quick sort b) Merge sort c) Heap sort a) Insertion into a B-tree b) Deletion from B-tree a) Insertion into an AVL tree b) Deletion from an AVL tree implement kruskals algorithm to generate a minimum spanning tree Prims algorithm to generate a minimum spanning tree implement all the functions of a dictionary (ADT) using hashing (additional program) Binary Tree Traversal using Recursion

6-12 13-19 20-23 24-30 31-34 35-42 43-48 49-53 54-58 59-69 70-71 72-74 75-81

82-90

SCITS, KNR

Department of CSE

ADSA Lab Manual

C++ Programming Language: 1. The C++ programming language is the advancement to the normal procedure oriented languages like COBOL, FORTRAN, C etc. 2. In case of the object oriented programming (OOP) languages like C++ the data doesnt flow freely around the system where as it is viewed as a sequence of things such as reading, calculating and printing in case of procedure oriented languages. Data flow freely around the system in this case. 3. The OOP allows decomposition of a problem into number of entities called objects and builds data and functions around the objects. The procedure oriented consists of writing a list of instructions. These instructions grouping into functions. 4. This OOP deals with the real world problems where as procedure oriented doesnt model real world problems very well. 5. The principles of the OOP are Encapsulation, Data Abstraction, Inheritance, Polymorphism, and Dynamic Binding etc. Applications of C++: C++ is a versatile language for handling very large programs. It is suitable for virtually any programming task including development of editors, compilers, databases, communication systems and any complex real-life application systems. 1. Since C++ allows us to create hierarchy-related objects, we can build special object-oriented libraries, which can be used later by many programmers. 2. While C++ is able to map the real-world problem properly, the C part of C++ gives the language the ability to get close to the machine-level details. 3. C++ programs are easily maintainable and expandable. When a new feature needs to be implemented, if is very easy to add to the existing structure of an object. 4. It is expected that C++ will replace C as a general-purpose language in the near future. C++ Compiler: 1 2. 3. 4. The file can be stored in C++ like .cpp & .cxx. Here we use CC command to compile the program like cc.example.c The source code available in example.c The compiler would produce an object file example.o and then automatically link with the library functions to produce an executable file. 5. Executable file name is a.out. SCITS, KNR 4

Department of CSE

ADSA Lab Manual

C++ Compilation: 1. Create and save the source files using under the file options. 2. Edit them under the Edit option. 3. Compile the program under the compile option and execute it under the Run option. 4. The Run option can be used without compiling the source code. In this case, the Run command causes the system to compile, link and run the program in one step. 5. A program spread over multiple files can be compiled as cc file1.c file2.0 6. The statement compiles only the file file1.c and links with previously compiled file2.0 7. This is useful when only one of the files needs to be modified. The files that arent modified need not be compiled again. Sample Program: #include<iostream.h> #include<conio.h> void main() { cout<< Hello welcome to CPP; }

SCITS, KNR

Department of CSE

ADSA Lab Manual

Experiment 1: Problem Statement: Write a C++ Programs to implement the following using an Array a) Stack ADT b) Queue ADT a) Solution Design: Design a class named stack which has member variables top, an array s [], ele, ch, I. All member variables have to be global. Design 3 public methods, one to push the elements into the stack; second one to pop from stack and the third is to display the elements in the stack. Class Name: Stack Properties/Member Variables: int top=-1, ele, ch, I, s []; Constructors: None. Public Interface: void push (), pop (), display (); Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Creates a Stack object. 2. Calls the method push () on the above object and pushes the element into the stack, calls method pop () to pop the elements out of the stack and the method display () to display the elements from the stack. 3. If the stack is full when pushing, this method prints Stack overflow, if stack is empty when popping, this displays Stack underflow, and if to display when no elements are present in the stack, this displays that the stack is empty. Test Cases: Test 1: Enter the choice for 1.push 2.pop 3.display Input: ch=1 Expected Output: enter the element to push Input: n=5 Test 2: Input: ch=1 Expected Output: enter the element to push Input: n=3 Test 3: Input: ch=3 Expected Output: the elements are: 3 5 SCITS, KNR 6

Department of CSE

ADSA Lab Manual

Test 4: Input: ch=2 Expected Output: deleted element is 3 Reference Implementation: ####################################################################
File: stack.cpp

#include<iostream.h> #include<conio.h> #include<process.h> #define max 5 int top=-1,s[max],ele,ch,i; template<class t> class stack { public: void push(void); void pop(void); void display(void); }; template<class t> void stack<t>::push(void) { if(top==max-1) { cout<<"stack overflows"; } else { cout<<"enter the element to push"; cin>>ele; top++; s[top]=ele; } } template<class t> void stack<t>::pop(void) { if(top==-1) { cout<<"stack underflow"; } else SCITS, KNR 7

Department of CSE

ADSA Lab Manual

{ cout<<"deleted element is:"<<s[top]<<endl; top--; } } template<class t> void stack<t>::display(void) { if(top==-1) { cout<<"stack is empty"; } else { for(i=0;i<=top;i++) { cout<<"the elements are:"<<s[top]<<endl; } } } int main() { clrscr(); stack<int>s; while(ch<=3) { cout<<"menu\n 1.push 2.pop 3.display 4.exit"<<endl; cin>>ch; switch(ch) { case 1:s.push(); break; case 2:s.pop(); break; case 3:s.display(); break; case 4:exit(0); } } getch(); return(0); }

SCITS, KNR

Department of CSE

ADSA Lab Manual

#################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program. Possible Enhancements: The size of the array can be dynamically created instead of creating it statically. Whenever an overflow condition arises instead of displaying the message we can add a method that can create the double size of the array as before to insert the overflowed element.

b) Solution Design: Design a class named Queue1 which has r, f, ele, q [max],ch,i as member variables. All member variables have to be global. Design 3 public methods, one to insert the SCITS, KNR 9

Department of CSE

ADSA Lab Manual

elements into the queue, second to delete the elements from the queue, and the other to display the elements in the queue. Class Name: Queue1 Properties/Member Variables: int r=0, f=0, ele, q [max], ch, i Public Interface: void insert (), void delete (), void display () Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create the queue1 object. 2. Calls the method insert () to insert the elements into the queue, method del () to delete the elements from the queue and the method display () to display the elements from the queue. 3. If inserted values exceed the max value of queue It displays queue overflow, if to delete from empty queue it displays queue underflow and if to display the elements from empty queue it displays queue is empty. Test Cases: Test 1: Enter the choice for 1.insert 2.delete 3.display Input: ch=1 Expected Output: enter the element to insert Input: n=5 Test 2: Input: ch=1 Expected Output: enter the element to element Input: n=3 Test 3: Input: ch=3 Expected Output: the elements are: 3 5 Test 4: Input: ch=2 Expected Output: deleted element is 3 Reference Implementation: ####################################################################
File: queue1.cpp

#include<iostream.h> #include<conio.h> #include<process.h> #define max 5 int r=0,f=0,ele,q[max],ch,i; template<class t> class queue1 SCITS, KNR 10

Department of CSE

ADSA Lab Manual

{ public: void insert(); void del(); void display(); }; template<class t> void queue1<t>::insert(void) { if(r==max) { cout<<"queue is overflow"<<endl; } else{ cout<<enter the element to insert cin>>ele; q[r++]=ele; } } template<class t> void queue1<t>::del(void) { if(f==r) { cout<<"queue is underflow"<<endl; } else { cout<<"deleted element is"<<q[f++]; } } template<class t> void queue1<t>::display(void) { if(f==r) { cout<<"queue is empty"<<endl; } else { for(i=f;i<r;i++) { SCITS, KNR 11

Department of CSE

ADSA Lab Manual

cout<<"queue is "<<q[i]<<endl; } } } int main() { clrscr(); queue1<int>q; while(ch<=3) { cout<<"menu 1.insert 2.delet 3.display 4.exit"; cin>>ch; switch(ch) { case 1:q.insert(); break; case 2:q.del(); break; case 3:q.display(); break; } } getch(); return(0); } #################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program. Possible Enhancements: The size of the array can be dynamically created instead of creating it statically. Whenever an overflow condition arises instead of displaying the message we can add a method that can create the double size of the array as before to insert the overflowed element.

SCITS, KNR

12

Department of CSE

ADSA Lab Manual

Experiment 2: Problem Statement: Write a C++ Programs to implement the following using an singly linked list a) Stack ADT b) Queue ADT a) Solution Design: Design a class Stlink which has a structure node to represent a linked list which is a global. Create 2 links temp, top. All these variables are global. Design 3 public methods, one to push the elements into the stack; second one to pop from stack and the third is to display the elements in the stack. Class Name: Stlink Properties/Member Variables: temp, top Public Interface: void push (), pop (), display (). Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create a stlink object. 2. Calls the method push () on the above object and pushes the element into the stack, calls method pop () to pop the elements out of the stack and the method display () to display the elements from the stack. 3. If the stack is full when pushing, this method prints Stack overflow, if stack is empty when popping, this displays Stack underflow, and if to display when no elements are present in the stack, this displays that the stack is empty. Test Cases: Test 1: Enter the choice for 1.push 2.pop 3.display Input: ch=1 Expected Output: enter the element to push Input: n=5 Test 2: Input: ch=1 Expected Output: enter the element to push Input: n=3 Test 3: Input: ch=3 Expected Output: the elements are: 3 5 Test 4: SCITS, KNR 13

Department of CSE

ADSA Lab Manual

Input: ch=2 Expected Output: deleted element is 3 Reference Implementation: File: stlink.cpp #include<iostream.h> #include<conio.h> struct node { int info; struct node *link; }*p,*temp,*top=NULL; template<class t> class stlink { public: void push(void); void pop(void); void display(void); }; template<class t> void stlink<t>::push(void) { int n; p=new node; cout<<"enter the nodes"<<endl; cin>>n; p->info=n; p->link=top; top=p; } template<class t> void stlink<t>::pop(void) { if(top==NULL) cout<<"there are no nodes"<<endl; else cout<<"deleted element is"<<top->info; top=top->link; } template<class t> void stlink<t>::display(void) { if(top==NULL) cout<<"no nodes"; SCITS, KNR 14

Department of CSE

ADSA Lab Manual

else { temp=top; while(temp!=NULL) { cout<<"elements are->"<<temp->info; temp=temp->link; } } } int main() { clrscr(); stlink<int>s; int ch=0; cout<<"1.push;2.pop;3.display\n"; while(ch<=3) { cout<<"enter your choice"; cin>>ch; switch(ch) { case 1:s.push(); break; case 2:s.pop(); break; case 3:s.display(); break; } } getch(); return(0); } Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program. Possible Enhancements: As this is created using a linked list the memory can be created dynamically. So, there can be no enhancements further.

SCITS, KNR

15

Department of CSE

ADSA Lab Manual

b) Solution Design: Design a class queue1 which has structure queue as global. It is used to represent a linked list. The members of this structure are data, next. Create 2 links front, rear. Design 3 public methods, one to insert the elements into the queue, second to delete the elements from the queue, and the other to display the elements in the queue. Class Name: Queue1 Properties/Member Variables: rear, front, next Public Interface: void insert (), void del (), void display () Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create the queue1 object. 2. Calls the method insert () to insert the elements into the queue, method del () to delete the elements from the queue and the method display () to display the elements from the queue. 3. If inserted values exceed the max value of queue It displays queue overflow, if to delete from empty queue it displays queue underflow and if to display the elements from empty queue it displays queue is empty. Test Cases: Test 1: Enter the choice for 1.insert 2.delete 3.display Input: ch=1 Expected Output: enter the element to insert Input: n=5 Test 2: Input: ch=1 Expected Output: enter the element to element Input: n=3 Test 3: Input: ch=3 Expected Output: the elements are: 3 5 Test 4: Input: ch=2 Expected Output: deleted element is 3

SCITS, KNR

16

Department of CSE

ADSA Lab Manual

Reference Implementation: ####################################################################


File: QLL.cpp

#include<iostream.h> #include<conio.h> #include<process.h> struct queue { int data; struct queue *next; }*p,*rear=NULL,*front=NULL,*temp; template<class t> class queue { public: void insert(void); void del(void); void display(void); }; template<class t> void queue<t>::insert(void) { int x; cout<<"enter element to be inserted:"; cin>>x; p=new queue; p->data=x; p->next=NULL; if(front==NULL) { front=p; rear=p; } else { rear->next=p; rear=p; } }

SCITS, KNR

17

Department of CSE

ADSA Lab Manual

template<class t> void queue<t>::del(void) { if(front==NULL) { cout<<"queue underflows\n"<<endl; } else { cout<<"deleted ele is:"; cout<front->data; front=front->next; } } template<class t> void queue<t>::display(void) { if(front==NULL) cout<<"queue empty";<<endl; else { temp=front; cout<<"ele in the queue are:"; while(temp!=NULL) { cout<<temp->data; cout<<"->"; temp=temp->next; } } } int main() { clrscr(); int ch; queue<int>q; do { cout<<"\n menu 1.insert 2.delet 3.display"; cout<<"enter choice:"; cin>>ch; switch(ch) { case 1:q.insert();break; SCITS, KNR 18

Department of CSE

ADSA Lab Manual

case 2:q.del();break; case 3:q.display();break; case 4:exit(0); } while(ch!=4) } getch(); return(0); } #################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program. Possible Enhancements: As this is created using a linked list the memory can be created dynamically. So, there can be no enhancements further.

SCITS, KNR

19

Department of CSE

ADSA Lab Manual

Experiment 3: Deque ADT Problem Statement: Write a C++ programs to implement the Deque (double ended queue) ADT using arrays. Solution Design: Design a class named Dequeue which has front1, rear1, front2, rear2, size as member variables. All member variables have to be private. Design 6 public methods, one is Dequeue constructor which creates the size of the array dynamically, the other methods are to insert into the queue from the front and another to insert from the rear, the methods to delete the elements from the queue are from the front and from rear ends and the method display () to print the elements from the queue. Class Name: Dequeue Properties/Member Variables: int front1, rear1, front2, rear2, size; Constructors: dequeue() Public Interface: void insertf (), insertr (), delf (), delr (), display (); Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create a dequeue object which calls the methods of the class. 2. Calls the method insertf() to insert the elements from the front end, and the method insertr () to insert the elements from the rear end, the methods delf(), delr() to delete the elements the queue from the front and rear ends, and display () method to display the elements in the queue. 3. If the queue is full, then the element when inserted will not be inserted and displays queue overflow and when to remove an element from an empty queue it displays queue underflow, and for displaying in the same condition will show queue is empty. Test Cases: Enter the choice 0. exit 1. insert front 2. insert rear 3. delete front 4. delete rear 5. display Test 1: Input: ch=1 Expected Output: enter the element to insert Input: n=5 Test 2: Input: ch=2 Expected Output: enter the element to element Input: n=3 Test 3: Input: ch=5 SCITS, KNR 20

Department of CSE

ADSA Lab Manual

Expected Output: the elements are: 3 5 Test 4: Input: ch=4 Expected Output: deleted element is 3 Reference Implementation: ####################################################################
File: Dequeue.cpp

#include<iostream.h> #include<conio.h> template<class t> class dequeue { int front1,rear1,front2,rear2,size; t *a; public: dequeue(); void insertf(); void insertr(); void delf(); void delr(); void display(); }; template<class t> dequeue<t>::dequeue() { front1=rear1=0; cout<<"\n enter the size:"; cin>>size; a=new t[size]; front2=rear2=size-1; for(int i=0;i<size;i++) a[i]=NULL; } template<class t> void dequeue<t>::insertf() { if(rear1==size||rear1>rear2) cout<<"\n queue is full"; else { cout<<"\n enter the no:"; cin>>a[rear1]; rear1++; } SCITS, KNR 21

Department of CSE

ADSA Lab Manual

} template<class t> void dequeue<t>::insertr() { if(rear2<rear1||rear2<0) cout<<"\n queue is full"; else { cout<<"\n enter the no:"; cin>>a[rear2]; rear2--; } } template<class t> void dequeue<t>::delf() { if(front1==size) cout<<"\n queue is empty"; else { int no; cout<<a[front1]; a[front1]=NULL; front1++; } } template<class t> void dequeue<t>::delr() { if(front2<0) cout<<"\n queue is empty"; else { cout<<a[front2]; a[front2]=NULL; front2--; } } template<class t> void dequeue<t>::display() { if(size==0) cout<<"\n queue is empty"; else { SCITS, KNR 22

Department of CSE

ADSA Lab Manual

for(int i=0;i<size;i++) { cout<<a[i]<<" "; } } }

void main() { clrscr(); dequeue<int> a; int choice; do { cout<<"\n 0-exit,1-insert front,2-insert rear,3-del front,4-del rear,5-display"; cin>>choice; switch(choice) { case 1:a.insertf(); break; case 2: a.insertr(); break; case 3: a.delf(); break; case 4: a.delr(); break; case 5: a.display(); break; } }while(choice!=0); }

#################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program. Possible Enhancements: The size of the array can be dynamically created instead of creating it statically. Whenever an overflow condition arises instead of displaying the message we can add a method that can create the double size of the array as before to insert the overflowed SCITS, KNR 23

Department of CSE

ADSA Lab Manual

element. Experiment 4: BinarySearchTree operations Problem Statement: Write a C++ program to perform the following operations: a) Insert an element into a binary search tree b) Delete an element from a binary search tree c) Search for a key element in a binary search tree Solution Design: Design a class Node which is used for the linked list declared as friend of class BST, has members data, lchild, rchild. These members are private. Design the actual class BST which has the member variable root of class Node type declared as private. Design 6 methods one for inserting the elements into the BST, next to delete an element from the BST , another to search an element in the BST, the method to display the elements using another method preorder(), the destroy() method to free the nodes created. All the methods need to be declared public. Class Name: BST Properties/Member Variables: root Public Interface: void destroy (Node<T> *p), insert (const T &e), del (const T &k), display (), preorder (Node<T> *p); bool search (const T &k); Constructors: BST () Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create the BST object. 2. Calls the method insert () to insert the elements into the BST, the method delete () to delete the element from the BST, the method search() to find whether an element is present in the BST or not, the method display () to print the elements in the BST. 3. If the element given for searching is not found, then the method search() displays element not found. Test Cases: Test 1: Enter the choice for 1.insert 2.search 3.delete 4.display 5.exit Input: ch=1 Expected Output: enter the element to insert Input: n=5 Test 2: SCITS, KNR 24

Department of CSE

ADSA Lab Manual

Input: ch=1 Expected Output: enter the element to insert Input: n=9 Test 3: Input: ch=1 Expected Output: enter the element to insert Input: n=3 Test 4: Input: ch=4 Expected Output: the elements are: 3 9 5 Test 5: Input: ch=3 Expected Output: enter the element to be deleted Input: n=5 Test 6: Input: ch=2 Expected output: enter the element to be searched Input: n=9 Expected output: element found Reference Implementation: ############################################################# File: BST.cpp #include<iostream.h> #include<conio.h> #include<process.h> enum bool{false,true}; template <class T> class Node { friend BST<T>; private: T data; Node<T> *lchild,*rchild; }; template <class T> class BST { public: BST() { root=NULL;} ~BST(); void destroy(Node<T> *p); bool search(const T &k); void insert(const T &e); void del(const T &k); SCITS, KNR 25

Department of CSE

ADSA Lab Manual

void display(); void preorder(Node<T> *p); private: Node<T> *root; }; template<class T> BST<T>::~BST() { destroy(root); } template<class T> void BST<T>::destroy(Node<T> *p) { if(p) { destroy(p->lchild); delete p; destroy(p->rchild); } } template<class T> bool BST<T>::search(const T &k) { Node<T> *p=root; while(p) { if(k<p->data) p=p->lchild; else if(k>p->data) p=p->rchild; else return true; } return false; } template<class T> void BST<T>::insert(const T &e) { Node<T> *p=new Node<T>; Node<T> *temp1=root,*temp2; p->data=e; p->lchild=p->rchild=NULL; if(root==NULL) root=p; SCITS, KNR 26

Department of CSE

ADSA Lab Manual

else { while(temp1) { temp2=temp1; if(e<temp1->data) temp1=temp1->lchild; else if(e>temp1->data) temp1=temp1->rchild; else{ cout<<"\n element is already there \n"; return; } } if(e>temp2->data) temp2->rchild=p; else temp2->lchild=p; } } template<class T> void BST<T>::del(const T &k) { Node<T> *p=root; Node<T> *temp=root,*temp2,*s; while(p) { if(k<p->data) { temp=p; p=p->lchild; } else if(k>p->data) { temp=p; p=p->rchild; } else { cout<<p->data<<"is deleted\n"; temp2=p; if(p->lchild) { s=p->lchild; while(s->rchild) { SCITS, KNR 27

Department of CSE

ADSA Lab Manual

temp2=s; s=s->rchild; } if(temp2!=p) temp2->rchild=s->lchild; else temp2->lchild=s->lchild; } else if(p->rchild) { s=p->rchild; while(s->lchild) { temp2=s; s=s->lchild; } if(temp2!=p) temp2->lchild=s->rchild; else temp2->rchild=s->rchild; } else { s=p; if(p->data>temp->data) temp->lchild=NULL; else temp->lchild=NULL; if(p==root) root=NULL; } p->data=s->data; p=NULL; delete s; return; } } cout<<"\n element not found"; return; } template<class T> void BST<T>::display() { if(root) preorder(root); else cout<<"there are no elements in bst\n"; SCITS, KNR 28

Department of CSE

ADSA Lab Manual

} template<class T> void BST<T>::preorder(Node<T> *p) { if(p) { cout<<p->data<<"\t"; preorder(p->lchild); preorder(p->rchild); } } void main() { BST<int> q; int i,ch,x; char t; clrscr(); do { cout<<"\n1.insert 2.search 3.delete 4.display 5.exit"; cout<<"\n enter the choice"; cin>>ch; switch(ch) { case 1: cout<<"\n enter the element to be inserted:"; cin>>x; q.insert(x); break; case 2: cout<<"\n enter the element to be search"; cin>>x; if(q.search(x)) cout<<x<<"is found"; else cout<<"element not found"; break; case 3: cout<<"\nenter the element to be deleted"; cin>>x; q.del(x); break; case 4: q.display(); break; case 5: exit(0); default: cout<<"\n entered wrong choice"; } cout<<"\n do u want to continue{y/n} :"; SCITS, KNR 29

Department of CSE

ADSA Lab Manual

cin>>t; }while(t!='n' &&t!='N'); } #################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program.

SCITS, KNR

30

Department of CSE

ADSA Lab Manual

Experiment 5: Circular Queue ADT Problem Statement: Write a C++ program to implement circular queue ADT using an array. Solution Design: Design a class CQ which has a[max], front, rear has its member variables. The member variables front, rear should be public variables, a[max] a private variable. Design 4 member functions where one is a constructor, the other next one is used to insert elements into the circular queue, another to delete the elements from the circular queue, the method display () to print the elements. Class Name: CQ Properties/Member Variables: a [max], front, rear Public Interface: void insert (), delete (), display () Constructors: CQ () Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create a CQ object. 2. Calls the method insert () to enter the elements into the circular queue, the method delete () to delete the elements from the circular queue, and the method display () to print the elements in the circular queue. 3. If the elements inserted into the circular queue exceed the max size, then if displays CQ overflow, similarly if the element is to be deleted from the empty queue it displays CQ underflow, and in case of displaying the empty it displays CQ empty. Test Cases: Enter the choice for 1.insert 2.delete 3.display 4.exit Test 1: Enter the choice for 1.insert 2.delete 3.display Input: ch=1 Expected Output: enter the element to insert Input: n=5 Test 2: Input: ch=1 Expected Output: enter the element to element Input: n=3 Test 3: Input: ch=3 Expected Output: the elements are: 3 5 Test 4: SCITS, KNR 31

Department of CSE

ADSA Lab Manual

Input: ch=2 Expected Output: deleted element is 3 Reference Implementation: #################################################################### File: CQ.cpp #include<iostream.h> #include<conio.h> #include<process.h> #define max 5 class CQ { int a[max]; public: int front, rear; CQ() { rear=front=-1; } void insert(),del(),display(); }; void CQ::insert() { if(((rear==max-1)&&(front==0))||(front==rear+1)) cout<<"CQ overflow"; else { int n; cout<<"enter the element to insert"; cin>>n; if(rear!=max-1) { a[++rear]=n; if(front==-1) front++; } else { rear=-1; a[++rear]=n; } } } void CQ::del() SCITS, KNR 32

Department of CSE

ADSA Lab Manual

{ if(rear==-1) cout<<"cq underflow"; else { cout<<"deleted element is"<<a[front++]; if(front==rear+1) front=rear=-1; if(front==max) front=0; } cout<<endl; } void CQ::display() { int i; if(rear==-1) cout<<"cq empty"; else if(front<=rear) for(i=front;i<=rear;i++) cout<<"\t"<<a[i]; else { for(i=front;i<=max-1;i++) cout<<"\t"<<a[i]; for(i=0;i<=rear;i++) cout<<"\t"<<a[i]; } cout<<endl; } void main() { CQ q; int ch,x; do { cout<<"1.insert 2.delete 3.display 4.exit"; cout<<"enter ur choice"; cin>>ch; switch(ch) { case 1: q.insert(); break; case 2: q.del(); SCITS, KNR 33

Department of CSE

ADSA Lab Manual

break; case 3:q.display(); break; case 4:exit(0); } } while(ch!=4); } #################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program. Possible Enhancements: The size of the array can be created dynamically without giving it statically. Whenever an overflow condition arises instead of displaying the message we can add a method that can create the double size of the array as before to insert the overflowed element.

SCITS, KNR

34

Department of CSE

ADSA Lab Manual

Experiment 6: Binary Tree Traversal using Non-Recursion Problem Statement: Write a c++ programs that use non-recursive functions to traverse the given binary tree a) Preorder b) Inorder c) Postorder Solution Design: Design a class Binary Search Tree which has struct tree as a node for representing every element in the tree. This is a private member. Design 6 methods one is a constructor and other to insert the elements into the tree, and there are 3 methods in which the elements can be displayed i.e., the print_preorder (), print_inorder (), print_postorder (). All these are to be declared to be public. Class Name: BinarySearchTree Properties/Member Variables: struct tree_node Public Interface: void print_postorder (), print_inorder (), print_preorder (), insert (). Private Methods: void inorder(), preorder(), postorder() Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. Test Cases: Enter your choice: 1. Insertion/Creation 2. In-Order Traversal 3. Pre-Order Traversal 4. Post-Order Traversal 5. Exit Test 1: Input: ch=1 Expected Output: Enter the element to be inserted Input: n=5 Test 2: Input: ch=1 Expected Output: Enter the element to be inserted Input: n=9 Test 3: Input: ch=1 Expected Output: Enter the element to be inserted Input: n=7 Test 4: Input: ch=2 Expected Output: Inorder-Traversal : 5 9 7 Test 5: Input: ch=3 Expected Output: Preorder-Traversal : 9 5 7 Test 6: Input: ch=4 SCITS, KNR 35

Department of CSE

ADSA Lab Manual

Expected Output: Postorder-Traversal : 5 7 9

Reference Implementation: Using NonRecursive #################################################################### File: BinarySearchTree BINARY TRAVERSALS USING NON RECURSIVE /*Binary search tree with all the Recursive and non Recursive traversals*/ #include<iostream.h> #include<conio.h> #include<stdlib.h> class binarynode { public: int data; binarynode *left; binarynode *right; }; class binsrctree { private: binarynode *root; void inorder(binarynode *); void preorder(binarynode *); void postorder(binarynode *); public: binsrctree() { root=NULL; } void insert(int ); void print_inorder(); void print_preorder(); void print_postorder(); }; class stack { int top; SCITS, KNR 36

Department of CSE

ADSA Lab Manual

binarynode *stackel[20]; public: stack() { top=-1; } void push(binarynode *); binarynode* pop(); int empty() { if(top==-1) return(1); return(0); } }; void stack::push(binarynode *node) { stackel[++top]=node; } binarynode *stack::pop() { return(stackel[top--]); } class stack_int { int top; int stack_int[20]; public: stack_int() { top=-1; } void push(int flag); int pop(); int empty_int() { if(top==-1) return(1); return(0); } }; SCITS, KNR 37

Department of CSE

ADSA Lab Manual

void stack_int::push(int flag) { stack_int[++top]=flag; } int stack_int::pop() { return(stack_int[top--]); } /*---------------------------------------------------------------------*/ /* FUNCTION TO INSERT A NODE IN THE TREE */ /*---------------------------------------------------------------------*/ void binsrctree::insert(int val) { binarynode *temp,*prev,*curr; temp=new binarynode; temp->data=val; temp->left=temp->right=NULL; if(root==NULL) { root=temp; } else { curr=root; while(curr!=NULL) { prev=curr; if(temp->data<curr->data) curr=curr->left; else curr=curr->right; } if(temp->data<prev->data) prev->left=temp; else prev->right=temp; } } /*--------------------------------------------------*/ /*INORDER NON RECURSIVE TRAVERSAL*/ /*--------------------------------------------------*/ SCITS, KNR 38

Department of CSE

ADSA Lab Manual

void binsrctree::inorder(binarynode *root) { stack stk; binarynode *temp; if(root!=NULL) { temp=root; do { while(temp!=NULL) { stk.push(temp); temp=temp->left; }/*end while*/ if(!stk.empty()) { temp=stk.pop(); cout<<temp->data<<" "; temp=temp->right; }/*end if*/ else break; }while(1); /*end do while*/ }/* end if */ else cout<<" Empty tree"; } /*end function */ /*--------------------------------------------------*/ /*PREORDER NON RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::preorder(binarynode *root) { stack stk; binarynode *temp=root; stk.push(temp); while(!stk.empty()) { temp=stk.pop(); SCITS, KNR 39

Department of CSE

ADSA Lab Manual

if(temp!=NULL) { cout<<temp->data<<" "; stk.push(temp->right); stk.push(temp->left); } } } /*--------------------------------------------------*/ /*POSTORDER NON RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::postorder(binarynode *root) { stack stk; stack_int stk1; int flag; binarynode *temp=root; do { if(temp!=NULL) { stk.push(temp); stk1.push(1); temp=temp->left; } else { if(stk.empty()) break; temp=stk.pop(); flag=stk1.pop(); if(flag==2) { cout<<temp->data; temp=NULL; } /*end if */ else { stk.push(temp); stk1.push(2); temp=temp->right; SCITS, KNR 40

Department of CSE

ADSA Lab Manual

} /* end else */ } /* end if */ }while(1);/*end do while*/ }/*end function*/ /*--------------------------------------------------*/ /*FUNCTION TO PRINT INORDER NON RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::print_inorder() { cout<<" "; inorder(root); cout<<" "; } /*--------------------------------------------------*/ /*FUNCTION TO PRINT PREORDER NON RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::print_preorder() { cout<<" "; preorder(root); cout<<" "; } /*--------------------------------------------------*/ /*FUNCTION TO PRINT POSTORDER NON RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::print_postorder() { cout<<" "; postorder(root); cout<<" "; } /*--------------------------------------------------*/ /* MAIN FUNCTION */ /*---------------------------------------------------*/ void main() SCITS, KNR 41

Department of CSE

ADSA Lab Manual

{ binsrctree BST; int ch,element; clrscr(); do { cout<<"1. Insert a node in binary tree"; cout<<"2. Inorder traversal"; cout<<"3.preorder traversal"; cout<<"4. postorder traversal"; cout<<"5. Exit \nEnter your choice"; cin>>ch; switch(ch) { case 1: cout<<"Enter the element you wnat to insert"; cin>>element; BST.insert(element); break; case 2: cout<<"Inorder traversal"; BST.print_inorder(); break; case 3: cout<<preorder traversal"; BST.print_preorder(); break; case 4: cout<<"postorder traversal"; BST.print_postorder(); break; case 5:exit(1); } }while(ch!=5); }

Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program.

SCITS, KNR

42

Department of CSE

ADSA Lab Manual

Experiment 7: Implementation of BFS and DFS Problem Statement: Write a C++ Programs for implementation of BFS AND DFS for a given graph Solution Design: Design a main class of the graphs. It contains the 3 methods one to create a graph, and the remaining 2 are for the searches that can be made on the graph i.e., dfs, and bfs. These are declared globally. The struct node, link are the 2 structures that are created to specify the link between the nodes. Class Name: main Properties/Member Variables: struct link, node, start, p, q. Constructors: None Public Interface: void create (), dfs (), bfs () Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create a main class which calls the methods create () to form the graph, the method dfs () to traverse the graph in the depth first search order, and the method bfs () to traverse the graph in the breadth first search order. 2. These dfs and bfs methods will display the elements in their respective order. Test Cases: Graph: 1-2, 1-4, 2-3, 3-5, 3-6, 4-6, 6-7 Enter your choice: 1.BFS 2.DFS 3.Exit. Test 1: Input: ch=1 Expected Output: Breadth First Search: 1-2-3-4-5-6-7 Test 2: Input: ch=2 Expected Output: Depth First Search: 1-2-3-5-6-7-4 Reference Implementation: #################################################################### File: Graph.cpp #include<conio.h> #include<iostream.h> #include<stdlib.h> void create(); // For creating a graph void dfs(); // For Deapth First Search(DFS) Traversal. SCITS, KNR 43

Department of CSE

ADSA Lab Manual

void bfs(); // For Breadth First Search(BFS) Traversal. struct node // Structure for elements in the graph { int data,status; struct node *next; struct link *adj; }; struct link // Structure for adjacency list { struct node *next; struct link *adj; }; struct node *start, *p, *q; struct link *l, *k; int main() { int choice; clrscr(); create(); do { cout<<"-----------------------"; cout<<"1: DFS 2: BSF 3: Exit \nEnter your choice: "; cin>>choice; switch(choice) { case 1: dfs(); break; case 2: bfs(); break; case 3: exit(0); break; default: cout<<"Incorrect choice! \nRe-enter your choice."; getch(); } }while(choice!=3); return 0; } void create() // Creating a graph { int dat,flag=0; SCITS, KNR 44

Department of CSE

ADSA Lab Manual

start=NULL; cout<<" Enter the nodes in the graph(0 to end): "; while(1) { cin>>dat; if(dat==0) break; p=new node; p->data=dat; p->status=0; p->next=NULL; p->adj=NULL; if(flag==0) { start=p; q=p; flag++; } else { q->next=p; q=p; } } p=start; while(p!=NULL) { cout<<"Enter the links to "<<p->data<<" (0 to end) : "; flag=0; while(1) { cin>>dat; if(dat==0) break; k=new link; k->adj=NULL; if(flag==0) { p->adj=k; l=k; flag++; } else { l->adj=k; SCITS, KNR 45

Department of CSE

ADSA Lab Manual

} cout<<"-------------------------"; return; } // Deapth First Search(DFS) Traversal. void bfs() { int qu[20],i=1,j=0; p=start; while(p!=NULL) { p->status=0; p=p->next; } p=start; qu[0]=p->data; p->status=1; while(1) { if(qu[j]==0) break; p=start; while(p!=NULL) { if(p->data==qu[j]) break; p=p->next; } k=p->adj; while(k!=NULL) { q=k->next; if(q->status==0) SCITS, KNR 46

} p=p->next;

} q=start; while(q!=NULL) { if(q->data==dat) k->next=q; q=q->next; }

l=k;

Department of CSE

ADSA Lab Manual

} j=0; cout<<"Breadth First Search Results"; cout<<"--------------------------"; while(qu[j]!=0) { cout<<qu[j]<<" "; j++; } getch(); return; } // Breadth First Search(BFS) Traversal. void dfs() { int stack[25],top=1; cout<<"Deapth First Search Results"; cout<<"---------------------------"; p=start; while(p!=NULL) { p->status=0; p=p->next; } p=start; stack[0]=0; stack[top]=p->data; p->status=1; while(1) { if(stack[top]==0) break; p=start; while(p!=NULL) { SCITS, KNR 47

} j++;

} k=k->adj;

qu[i]=q->data; q->status=1; qu[i+1]=0; i++;

Department of CSE

ADSA Lab Manual

} cout<<stack[top]<<" "; top--; k=p->adj; while(k!=NULL) { q=k->next; if(q->status==0) { top++; stack[top]=q->data; q->status=1; } k=k->adj; } } getch(); return;

if(p->data==stack[top]) break; p=p->next;

#################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program.

SCITS, KNR

48

Department of CSE

ADSA Lab Manual

Experiment 8:Implementation of sorting methods Problem Statement: Write a C++ Programs to implement the following sorting algorithms a) Quick Sort b) Merge sort c) Heap Sort Solution Design: Design a class Sort which has the member variable a. This is a private variable. Design 4 methods one for the creation of the list and the other to display the elements in the sorted order by using the heap, merge, and quick sorts. This class contains 2 constructors one for the default allocation of size to the array of elements to be sorted, and the other constructor for dynamic allocation of size for the array. Class Name: Sort Properties/Member Variables: int a; Constructors: Sort (), Sort (int n) Public Interface: void create (), mergesort (), quicksort (), heapsort (), display () Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create a Sort object, which can call certain methods. 2. Calls the methods create () to insert the elements into the array, the method display () to print the elements in the array in the sorted order using the methods heapsort (), quicksort (), mergesort (). Test Cases: Test 1: Input: a []= {6,8,3,9,4} Expected Output: using any one of the sorts the sorted order is {3,4,6,8,9} Test 2: Input: a []={15,7,9,34,14} Expected Output: sorted order is: {7,9,14,15,34} Reference Implementation: #################################################################### File: sort. cpp #include<iostream.h> #include<conio.h> SCITS, KNR 49

Department of CSE

ADSA Lab Manual

#include<process.h> template<class T> class sort { private: int a; public: sort(){int a=new int[50];} sort(int n) { int a=new int[n]; } void create(); void heapsort(); void void void void void void }; display(); mergesort(); adjust(int [],int,int); swap(int a,int b); print(int [],int); merge(int [],int,int);

template<class T> void sort<T>::create() { cout<<"\n Enter the elements"; for(int i=0;i<5;i++) cin>>a[i]; } template<class T> void sort<T>::heapsort() { int i,n; cout<<"\n The adjusted List:"; for(i=(n-1)/2;i>=0;i--) adjust(a,i,n); for(i=n-1;i>=0;i--) { swap(&a[i+1],&a[0]); adjust(a,0,i); } } template<class T> void sort<T>::adjust(int &a[],int i,int n) { SCITS, KNR 50

Department of CSE

ADSA Lab Manual

int flag=0,j,k; k=a[i]; j=2*i+1; while((j<=n)&&!flag) { if((j<n)&&a[j]<a[j+1]) j++; if(k>=a[j]) { flag=1; } else { a[j-1/2]=a[j]; j=s*j+1; } } a[(j-1)/2]=k; } template<class T> void sort<T>::swap(int *p,int *q) { int i; t=*p; *p=*q; *q=*t; } template<class T> void sort<T>::print() { int i; for(i=0;i<n;i++) cout<<a[i]<<""; } template<class T> void sort<T>::mergesort() { int mid; msort(int a[],int low,int high); } template<class T> SCITS, KNR 51

Department of CSE

ADSA Lab Manual

void sort<T>::msort(int a[],int low,int high) { int mid; if(low<high) { mid=(high+low)/2; msort(a,low,mid); msort(a,mid+1,high); } } template<class T> void sort<T>::merge(int a[],int &m,int &n) { int b[5]; int i,j,k; i=1; j=m+1; k=1; while((i<=m)&&(j<=n)) { if(a[i]<=a[j]) b[k++]=a[i++]; else b[k++]=a[j++]; } while(i<=n) { b[k++]=a[i++]; } while(j<=n) b[k++]=a[j++]; for(k=1;k<=n;k++) a[k]=b[k]; } void main() { int c; sort<T> s; do { s.create(); cout<<"\n ** Menu **"; cout<<"\n 1:Heapsort 2:Mergesort 3:exit"; cin>>c; SCITS, KNR 52

Department of CSE

ADSA Lab Manual

swith(c) { case 1: s.heapsort(); break; case 2:s.mergesort(); break; case 3:exit(0); default: cout<<"\n Invalid choice"; } } while(c!=4); } #################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program.

SCITS, KNR

53

Department of CSE

ADSA Lab Manual

Experiment 9: B-Tree Operations Problem Statement: Write a C++ Programs to perform the following operations a) Insertion into a B-Tree b) Deletion from a B-Tree Solution Design: Design a class B_Tree which has the nodes as its member variables. All these variables are private. Design 6 methods one method to create the B-Tree and one method to insert the elements into the tree, one to delete the elements from the tree, another to insert into nonfull tree and to find an element in the tree. Class Name: B_Tree Properties/Member Variables: int i, n [] Constructors: None Public Interface: void insert (), insertNonFull (), delete (), create (), search (), splitChild (). Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create a B_Tree object and calls the methods. 2. Calls the method create () to create the initially the tree, another method insert () the elements into the tree, one method to splitChild when an ordering is required, another method search() to find whether an element is present in the tree or not, one method to delete the elements from the tree. 3. If the element to delete is not found in the tree then it displays element doesnt exists. Test Cases: Enter tour choice: 1. Create 2. Insert 3. Insertnonfull 4. Search 5. SplitChild 6. Delete 7. Exit; Test 1: Input: ch=1 Expected Output: enter the element to create: Input: n=8 Test 2: Input: ch=2 Expected Output: enter the element to insert: SCITS, KNR 54

Department of CSE

ADSA Lab Manual

Input: n=5 Test 3: Input: ch=2 Expected Output: enter the element to insert: Input: n=7 Test 4: Input: ch=6 Expected Output: enter the element to delete: Input: n=8

Reference Implementation: #################################################################### File: B-Tree.cpp #include<iostream.h> #include<conio.h> #include<process.h> class B_Tree { int i,n[]; public: void search(int,int); void create(T); void splitChild(int,int,int); void insert(int); void insertNonFull(int); void delete(int,int); } // B-Tree-Search(x, k) void B_Tree::search(int x,int k) { i <- 1 while i <= n[x] and k > keyi[x] do i <- i + 1 if i <= n[x] and k = keyi[x] then return (x, i) if leaf[x] then return NIL else Disk-Read(ci[x]) return B-Tree-Search(ci[x], k) } SCITS, KNR 55

Department of CSE

ADSA Lab Manual

// B-Tree-Create(T) void B_Tree::create(T) { x <- Allocate-Node() leaf[x] <- TRUE n[x] <- 0 Disk-Write(x) root[T] <- x } // B-Tree-Split-Child(x, i, y) void B_Tree::splitChild(int x,int i,int y) { z <- Allocate-Node() leaf[z] <- leaf[y] n[z] <- t - 1 for j <- 1 to t - 1 do keyj[z] <- keyj+t[y] if not leaf[y] then for j <- 1 to t do cj[z] <- cj+t[y] n[y] <- t - 1 for j <- n[x] + 1 downto i + 1 do cj+1[x] <- cj[x] ci+1 <- z for j <- n[x] downto i do keyj+1[x] <- keyj[x] keyi[x] <- keyt[y] n[x] <- n[x] + 1 Disk-Write(y) Disk-Write(z) Disk-Write(x) } // B-Tree-Insert(T, k) void B_Tree::insert(T,int k) { r <- root[T] if n[r] = 2t - 1 then s <- Allocate-Node() root[T] <- s leaf[s] <- FALSE n[s] <- 0 c1 <- r B-Tree-Split-Child(s, 1, r) B-Tree-Insert-Nonfull(s, k) SCITS, KNR 56

Department of CSE

ADSA Lab Manual

else B-Tree-Insert-Nonfull(r, k)

// B-Tree-Insert-Nonfull(x, k) void B_Tree::insertNonFull(int x,int k) { i <- n[x] if leaf[x] then while i >= 1 and k < keyi[x] do keyi+1[x] <- keyi[x] i <- i - 1 keyi+1[x] <- k n[x] <- n[x] + 1 Disk-Write(x) else while i >= and k < keyi[x] do i <- i - 1 i <- i + 1 Disk-Read(ci[x]) if n[ci[x]] = 2t - 1 then B-Tree-Split-Child(x, i, ci[x]) if k > keyi[x] then i <- i + 1 B-Tree-Insert-Nonfull(ci[x], k) } // B-Tree-Delete(x,k) void B_Tree::delete(int x,int k) { If leaf[x]!=NULL && key[x]<-k then leaf[x]=NULL; else cout<<element not exists; } void main() { int ch,n; B_Tree b; do { cout<<1.Create 2.Insert 3.Insertnonfull 4.Search 5.SplitChild 6.Delete 7.Exit; cout<<Enter your choice:; cin>>ch; switch(ch) { case 1: cout<<enter the element to create the B-Tree:; SCITS, KNR 57

Department of CSE

ADSA Lab Manual

cin>>n; b.create(x,n); break; case 2: cout<<enter the element cin>>n; b.insert(T,n); break; case 3: cout<<enter the element cin>>n; b.insertNonFull(x,n); break; case 4: cout<<enter the element cin>>n; b.search(x,n); case 5: b.splitChild(x,i,n); break; case 6: cout<<enter the element cin>>n; b.delete(x,n); break; case 7: exit(0); } }while(ch!=7); getch(); }

to be inserted;

when the tree is nonfull;

to be searched:;

to be deleted;

#################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program.

SCITS, KNR

58

Department of CSE

ADSA Lab Manual

Experiment 10: AVL Tree Operations Problem Statement: Write a C++ Programs to perform the following operations a) Insertion into an AVL Tree b) Deletion from an AVL Tree Solution Design: Design a class bstree, which has a structure node with members node left, right and int height which are declared globally. Also a struct node variable nodeptr declared as global. Design methods where one is to insert the elements into the AVL tree, and to find an element in the element, and to display the min and max elements in the tree and to display in the in, pre, and postorder traversals, and methods to delete the min and max values. Class Name: Bstree Properties/Member Variables: struct node, nodeptr Constructors: None Public Interface: void insert (), deletemin (), deletemax (), inorder (), postorder (), preorder (), find (), findmin (),findmax (). Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create a bstree object and call the methods. 2. Calls the method insert () to insert the element in the AVL tree, and 2 methods findmin (), findmax () to find min and max elements in the tree, and find() method to find an element in the tree, copy () method to copy the AVL tree to print in the inorder format, the method delete() to remove the elements from the AVL tree, and the tree traversals are used to display the elements, and height () method to find the levels of the AVL tree. Test Cases: Enter your choice: 1.Insertion 2.FindMin 3.FindMax 4.Find 5.Copy 6.Delete 7.Preorder 8.Inorder 9.Postorder 10.height Test 1: Input: ch=1 Expected Output: enter the element to be inserted: Input: n=7 Test 2: SCITS, KNR 59

Department of CSE

ADSA Lab Manual

Input: ch=1 Expected Output: Input: n=4 Test 3: Input: ch=1 Expected Output: Input: n=6 Test 4: Input: ch=1 Expected Output: Input: n=2 Test 5: Input: ch=2 Expected Output: Test 6: Input: ch=3 Expected Output: Test 7: Input: ch=6 Expected Output: Test 8: Input: ch=8 Expected Output:

enter the element to be inserted:

enter the element to be inserted:

enter the element to be inserted:

the minimum element is: 2 the maximum element is: 7 enter the element to be deleted : 2 the inorder traversal is : 4 6 7

Reference Implementation: #################################################################### File: AVLTrees.cpp /* Adelson Velseky Landis Tree */ # include <iostream.h> # include <stdlib.h> # include <conio.h> struct node { int element; node *left; node *right; int height; }; typedef struct node *nodeptr; class bstree SCITS, KNR 60

Department of CSE

ADSA Lab Manual

{ public: void insert(int,nodeptr &); void del(int, nodeptr &); int deletemin(nodeptr &); void find(int,nodeptr &); nodeptr findmin(nodeptr); nodeptr findmax(nodeptr); void copy(nodeptr &,nodeptr &); void makeempty(nodeptr &); nodeptr nodecopy(nodeptr &); void preorder(nodeptr); void inorder(nodeptr); void postorder(nodeptr); int bsheight(nodeptr); nodeptr srl(nodeptr &); nodeptr drl(nodeptr &); nodeptr srr(nodeptr &); nodeptr drr(nodeptr &); int max(int,int); int nonodes(nodeptr); }; // Inserting a node void bstree::insert(int x,nodeptr &p) { if (p == NULL) { p = new node; p->element = x; p->left=NULL; p->right = NULL; p->height=0; if (p==NULL) cout<<"Out of Space"; } else { if (x<p->element) { insert(x,p->left); if ((bsheight(p->left) - bsheight(p->right))==2) { if (x < p->left->element) p=srl(p); SCITS, KNR 61

Department of CSE

ADSA Lab Manual

else p = drl(p); } else if (x>p->element) { insert(x,p->right); if ((bsheight(p->right) - bsheight(p->left))==2) { if (x > p->right->element) p=srr(p); else p = drr(p); } } else cout<<"Element Exists"; } int m,n,d; m=bsheight(p->left); n=bsheight(p->right); d=max(m,n); p->height = d + 1; } // Finding the Smallest nodeptr bstree::findmin(nodeptr p) { if (p==NULL) { cout<<"Empty Tree"; return p; } else { while(p->left !=NULL) p=p->left; return p; } } // Finding the Largest nodeptr bstree::findmax(nodeptr p) { if (p==NULL) SCITS, KNR 62 }

Department of CSE

ADSA Lab Manual

} else { while(p->right !=NULL) p=p->right; return p; } } // Finding an element void bstree::find(int x,nodeptr &p) { if (p==NULL) cout<<"Element not found"; else if (x < p->element) find(x,p->left); else if (x>p->element) find(x,p->right); else cout<<"Element found !"; } // Copy a tree void bstree::copy(nodeptr &p,nodeptr &p1) { makeempty(p1); p1 = nodecopy(p); } // Make a tree empty void bstree::makeempty(nodeptr &p) { nodeptr d; if (p != NULL) { makeempty(p->left); makeempty(p->right); d=p; free(d); p=NULL; SCITS, KNR 63

cout<<"Empty Tree"; return p;

Department of CSE

ADSA Lab Manual

// Copy the nodes nodeptr bstree::nodecopy(nodeptr &p) { nodeptr temp; if (p==NULL) return p; else { temp = new node; temp->element = p->element; temp->left = nodecopy(p->left); temp->right = nodecopy(p->right); return temp; } } // Deleting a node void bstree::del(int x,nodeptr &p) { nodeptr d; if (p==NULL) cout<<"Element not found"; else if ( x < p->element) del(x,p->left); else if (x > p->element) del(x,p->right); else if ((p->left == NULL) && (p->right == NULL)) { d=p; free(d); p=NULL; cout<<" Element deleted !"; } else if (p->left == NULL) { d=p; free(d); p=p->right; cout<<" Element deleted !"; } else if (p->right == NULL) { d=p; SCITS, KNR 64

Department of CSE

ADSA Lab Manual

} else p->element = deletemin(p->right); } int bstree::deletemin(nodeptr &p) { int c; cout<<"inside deltemin "; if (p->left == NULL) { c=p->element; p=p->right; return c; } else { c=deletemin(p->left); return c; } } void bstree::preorder(nodeptr p) { if (p!=NULL) { cout<<p->element<<"-->"; preorder(p->left); preorder(p->right); } } // Inorder Printing void bstree::inorder(nodeptr p) { if (p!=NULL) { inorder(p->left); cout<<p->element<<"-->"; inorder(p->right); } } SCITS, KNR 65

p=p->left; free(d); cout<<" Element deleted !";

Department of CSE

ADSA Lab Manual

// PostOrder Printing void bstree::postorder(nodeptr p) { if (p!=NULL) { postorder(p->left); postorder(p->right); cout<<p->element<<"-->"; } } int bstree::max(int value1, int value2) { return ((value1 > value2) ? value1 : value2); } int bstree::bsheight(nodeptr p) { int t; if (p == NULL) return -1; else { t = p->height; return t; } } nodeptr bstree:: srl(nodeptr &p1) { nodeptr p2; p2 = p1->left; p1->left = p2->right; p2->right = p1; p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1; p2->height = max(bsheight(p2->left),p1->height) + 1; return p2; } nodeptr bstree:: srr(nodeptr &p1) { nodeptr p2; p2 = p1->right; p1->right = p2->left; p2->left = p1; p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1; SCITS, KNR 66

Department of CSE

ADSA Lab Manual

p2->height = max(p1->height,bsheight(p2->right)) + 1; return p2; } nodeptr bstree:: drl(nodeptr &p1) { p1->left=srr(p1->left); return srl(p1); } nodeptr bstree::drr(nodeptr &p1) { p1->right = srl(p1->right); return srr(p1); } int bstree::nonodes(nodeptr p) { int count=0; if (p!=NULL) { nonodes(p->left); nonodes(p->right); count++; } return count; }

int main() { clrscr(); nodeptr root,root1,min,max;//,flag; int a,choice,findele,delele,leftele,rightele,flag; char ch='y'; bstree bst; //system("clear"); root = NULL; root1=NULL; cout<<"AVL Tree"; cout<<"========"; do { SCITS, KNR 67

Department of CSE

ADSA Lab Manual

cout<<"1.Insertion 2.FindMin 3.FindMax; cout<<4.Find 5.Copy 6.Delete 7.Preorder; cout<<8.Inorder 9.Postorder 10.height "; cout<<"Enter the choice:"; cin>>choice; switch(choice) { case 1: cout<<"New node's value ?"; cin>>a; bst.insert(a,root); break; case 2: if (root !=NULL) { min=bst.findmin(root); cout<<"Min element :"<<min->element; } break; case 3: if (root !=NULL) { max=bst.findmax(root); cout<<"Max element :"<<max->element; } break; case 4: cout<<"Search node : "; cin>>findele; if (root != NULL) bst.find(findele,root); break; case 5: bst.copy(root,root1); bst.inorder(root1); break; case 6: cout<<"Delete Node ?"; cin>>delele; bst.del(delele,root); bst.inorder(root); break; case 7: cout<<"Preorder Printing... :"; bst.preorder(root); break; case 8: cout<<" Inorder Printing.... :"; bst.inorder(root); break; case 9: cout<<" Postorder Printing... :"; SCITS, KNR 68

Department of CSE

ADSA Lab Manual

bst.postorder(root); break; case 10: cout<<"Height and Depth is "; cout<<bst.bsheight(root); cout<<"No. of nodes:- "<<bst.nonodes(root); break; } cout<<"Do u want to continue (y/n) ?"; cin>>ch; }while(ch=='y'); return 0; } #################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program.

SCITS, KNR

69

Department of CSE

ADSA Lab Manual

Experiment 11: Implementation of Kruskals Algorithm Problem Statement: Write a C++ Programs to implement Kruskals algorithm to generate a minimum spanning tree Solution Design: Design a class Kruskal which has the members like weight, vertex, edge which are private variables. Design 2 methods one to create the graph, another method to develop the less cost for visiting the entire graph. Class Name: Kruskal Properties/Member Variables: vertex, edge, weight Constructors: None Public Interface: void create (), mincost (). Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create an object which calls the methods. 2. Calls the method create () to create the graph and the method mincost () to find the minimum cost for visiting the entire graph. Test Cases: Creating the graph with their respective weights: 1-(4)-4, 1-(2)-5, 4-(6)-6, 4-(1)-7, 5-(3)-6, 6-(4)-2, 2-(2)-3 Test: Input: Mincost Expected Output: the min_cost of the graph using Kruskals algorithm is: 17 Reference Implementation: #################################################################### File: Kruskal.cpp Graph& KruskalsAlgorithm (Graph const& g) { unsigned int const n = g.NumberOfVertices (); Graph& result = *new GraphAsLists (n); for (Vertex::Number v = 0; v < n; ++v) result.AddVertex (*new Vertex (v)); SCITS, KNR 70

Department of CSE

ADSA Lab Manual

PriorityQueue& queue = *new BinaryHeap (g.NumberOfEdges ()); Iterator& p = g.Edges (); while (!p.IsDone ()) { WeightedEdge& edge = dynamic_cast<WeightedEdge&> (*p); Int& weight = dynamic_cast<Int&> (edge.Weight ()); queue.Enqueue (*new Assoc (weight, edge)); ++p; } delete &p; Partition& partition = *new PartitionAsForest (n); while (!queue.IsEmpty () && partition.Count () > 1) { Assoc& assoc = dynamic_cast<Assoc&> (queue.DequeueMin ()); Edge& edge = dynamic_cast<Edge&> (assoc.Value ()); Vertex::Number const v0 = edge.V0 (); Vertex::Number const v1 = edge.V1 (); Set& s = partition.Find (Set::Element (v0)); Set& t = partition.Find (Set::Element (v1)); if (s != t) { partition.Join (s, t); result.AddEdge (*new Edge (result[v0], result[v1])); } delete &assoc; } delete &partition; delete &queue; return result; } #################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program.

SCITS, KNR

71

Department of CSE

ADSA Lab Manual

Experiment 12: Implementation of Prims Algorithm Problem Statement: Write a C++ Programs to implement Prims algorithm to generate a minimum spanning tree Solution Design: Design a class Prims which has the members like weight, vertex, edge which are private variables. Design 2 methods one to create the graph, another method to develop the less cost for visiting the entire graph. Class Name: Prims Properties/Member Variables: vertex, edge, weight Constructors: None Public Interface: void create (), mincost (). Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create an object which calls the methods. 2. Calls the method create () to create the graph and the method mincost () to find the minimum cost for visiting the entire graph. Test Cases: Creating the graph with their respective weights: 1-(4)-4, 1-(2)-5, 4-(6)-6, 4-(1)-7, 5-(3)-6, 6-(4)-2, 2-(2)-3 Test: Input: Mincost Expected Output: the min_cost of the graph using Prims algorithm is: 17 Reference Implementation: #################################################################### File: Prims.cpp Graph& PrimsAlgorithm (Graph const& g, Vertex const& s) { unsigned int const n = g.NumberOfVertices (); Array<TableEntry> table (n); PriorityQueue& queue = *new BinaryHeap (g.NumberOfEdges ()); table [s].distance = 0; SCITS, KNR 72

Department of CSE

ADSA Lab Manual

queue.Enqueue (*new Assoc (0, const_cast<Vertex&> (s))); while (!queue.IsEmpty ()) { Assoc& assoc = dynamic_cast<Assoc&> (queue.DequeueMin ()); Vertex& v0 = dynamic_cast<Vertex&> (assoc.Value ()); if (!table [v0].known) { table [v0].known = true; Iterator& p = g.EmanatingEdges (v0); while (!p.IsDone ()) { WeightedEdge& edge = dynamic_cast<WeightedEdge&> (*p); Vertex& v1 = edge.Mate (v0); Int& weight = dynamic_cast<Int&> (edge.Weight ()); int const d = weight; if (!table[v1].known && table[v1].distance > d) { table [v1].distance = d; table [v1].predecessor = v0; queue.Enqueue (*new Assoc (d, v1)); } ++p; } delete &p; } delete &assoc; } delete &queue; Graph& result = *new GraphAsLists (n); for (Vertex::Number v = 0; v < n; ++v) result.AddVertex (*new Vertex (v)); for (Vertex::Number v = 0; v < n; ++v) if (v != s) result.AddEdge (*new Edge ( result [v], result [table [v].predecessor])); return result; } #################################################################### Execution: SCITS, KNR 73

Department of CSE

ADSA Lab Manual

Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program.

SCITS, KNR

74

Department of CSE

ADSA Lab Manual

Experiment 13: Implementation of Hashing functions Problem Statement: Write a C++ Programs to implement all the functions of a dictionary (ADT) using hashing. Solution Design: Design a class Hashtable which has list array which is a private variable. Design 5 methods one is constructor, another is to insert the values into the table, another is to delete the elements from the table, one is to view the element in the hashtable, one is to find an element in the table. Class Name: Hashtable Properties/Member Variables: list table []; Constructors: Hashtable () Public Interface: void view (), bool insert (), remove (), type find () Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Create a hashtable object which calls the methods. 2. Calls the method insert () which inserts the elements into the table, the method remove () to remove the elements from the table, one method find () is to known whether an element is in the table or not, another method view () is to view the hash table. 3. If the element to search is not found in the table it will display element not found. Test Cases: Enter your choice: 1. Insert 2. Delete 3. Search 4. View 5. Exit Test 1: Input: ch=1 Expected Output: enter the element to insert: Input: n=5 Test 2: Input: ch=1 Expected Output: enter the element to insert: Input: n=6 Test 3: Input: ch=1 Expected Output: enter the element to insert: Input: n=2 Test 4: Input: ch=4 SCITS, KNR 75

Department of CSE

ADSA Lab Manual

Expected Output: Test 5: Input: ch=2 Expected Output: Input: n=6 Test 6: Input: ch=2 Expected Output: Input: n=2 Expected Output:

elements in the HashTable are: 5 6 2 enter the element to be deleted:

enter the element to find: element found

Reference Implementation: #################################################################### File: Hashing.cpp #include<iostream.h> #include<conio.h> #include<process.h> #ifndef _HASHTABLE_H #define _HASHTABLE_H #include #include #include #include "type.h" "list.h" "listiter.h" <string.h>

#define TABLE_SIZE 33 class Hashtable { public:

Hashtable(); bool insert (Type *); void view(); Type* find (char*); bool remove(char *); List* table[TABLE_SIZE]; int hash (char*); //hash function

private: }; #endif //_HASHTABLE_H SCITS, KNR 76

Department of CSE

ADSA Lab Manual

#include "hashtable.h" #define DEBUG 1 Hashtable::Hashtable() { for(int i = 0; i < TABLE_SIZE; i++) table[i] = 0; } //Hash Function: sum of the ASCII codes of the characters % TABLE_SIZE int Hashtable::hash (char *l) { int long sum = 0; int len = strlen(l); for(int i = 0; i < len; i++) sum += l[i]; return sum % TABLE_SIZE; } bool Hashtable::insert (Type* new_item) { int index; List* list; Node* p; index = hash(new_item->get_key()); if(DEBUG) cout<<"\nThe index given by a hashfunction is "<<index;

if(table[index] == 0){ table[index] = new List(*new_item); return true; } else { list = table[index]; p = list->finditem(*new_item); if(p == NULL) list->insert(*new_item); else p->setinfo(*new_item); SCITS, KNR 77

Department of CSE

ADSA Lab Manual

return true; } } return false; //should never get here

void Hashtable::view() { for(int i = 0; i < TABLE_SIZE; i++) { if(table[i] != 0 ){ List list = *table[i]; ListIter iter(list); while(!iter.done()) { if(strcmp(iter.value().get_key(), "*") != 0) cout << "Index: " << i << iter.value(); iter.next(); } } } }

Type* Hashtable::find (char* key) { int index, new_index; Type *item; List *list; Node *p; item = new Type(key); new_index = index = hash(key); if (table[index] == 0) return 0; list = table[index]; p = list->finditem(*item); if(p == NULL) return NULL; else { SCITS, KNR 78

Department of CSE

ADSA Lab Manual

*item = p->getinfo(); return item; } }

bool Hashtable::remove(char *key) { int index, new_index; List list; new_index = index = hash(key); if (table[index] == 0) return false; list = *table[index]; ListIter iter(list); while(!iter.done()) { Node *node = iter.lookup(); Type value = node->getinfo(); if (strcmp(value.get_key(), key) == 0) { value.set_key("*"); node->setinfo(value); return true; } iter.next(); } } return false;

void main() { Hashtable *table; table = new Hashtable(); int flag = 1; while(flag) { int choice; SCITS, KNR 79

Department of CSE

ADSA Lab Manual

cout << "\n 1. Insert 2. Delete 3. Search 4. View 5. Exit ; cout << "\n Please enter your choice: "; cin >> choice; cin.get(); if(choice == 5) flag = 0; else if(choice == 1) { char last_name[20]; char first_name[20]; char key[11]; double gpa; Student *st; bool result; cout << "\nEnter the key" << endl; cin >> key; cin.get (); cout << "\nEnter last name" << endl; cin >> last_name; cin.get(); cout << "\nEnter first name" << endl; cin >> first_name; cin.get (); cout << "\nEnter GPA" << endl; cin >> gpa; cin.get(); st = new Type(last_name, first_name, gpa, key); result = table->insert(st); if(result == true) cout<<endl<<"The record was successfully inserted" << endl; else cout << endl << "The record was not inserted" << endl; } else if(choice == 2) { char key[20]; bool result; 80

SCITS, KNR

Department of CSE

ADSA Lab Manual

cout << "\nEnter the key" << endl; cin >> key; cin.get (); result = table->remove(key); if(result == true) cout<<"\nThe record was successfully deleted from the table"; else cout << "The record was not found." << endl; } else if(choice == 3) { char key[20]; Student *s; cout << "\nEnter the key" << endl; cin >> key; cin.get (); s = table->find(key); if(s) cout << "Found record:" << *s; else cout << endl << "The record was not found" << endl;

} else if(choice == 4) { table->view(); } else cout << "Invalid choice" << endl; } };

#################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program.

SCITS, KNR

81

Department of CSE

ADSA Lab Manual

ADDITIONAL PROGRAMS

SCITS, KNR

82

Department of CSE

ADSA Lab Manual

Experiment 14: Binary Tree Traversal using Recursion Problem Statement: Write a c++ programs that use recursive functions to traverse the given binary tree a) Preorder b) Inorder c) Postorder Solution Design: Design a class Binary Search Tree which has struct tree as a node for representing every element in the tree. This is a private member. Design 6 methods one is a constructor and other to insert the elements into the tree, the other to delete from the tree, and there are 3 methods in which the elements can be displayed i.e., the preorder (), inorder (), postorder (). All these are to be declared to be public. Class Name: BinarySearchTree Properties/Member Variables: struct tree_node Public Interface: void print_postorder (), print_inorder (), print_preorder (), insert (), remove (). Private Methods: None Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. Test Cases: Enter your choice: 1. Insertion/Creation 2. In-Order Traversal 3. Pre-Order Traversal 4. Post-Order Traversal 5. Removal 6. Exit Test 1: Input: ch=1 Expected Output: Enter the element to be inserted Input: n=5 Test 2: Input: ch=1 Expected Output: Enter the element to be inserted Input: n=9 Test 3: Input: ch=1 Expected Output: Enter the element to be inserted Input: n=7 Test 4: Input: ch=2 Expected Output: Inorder-Traversal : 5 9 7 Test 5: Input: ch=3 Expected Output: Preorder-Traversal : 9 5 7 SCITS, KNR 83

Department of CSE

ADSA Lab Manual

Test 6: Input: ch=4 Expected Output: Postorder-Traversal : 5 7 9 Reference Implementation: Using Recursive #################################################################### File: BinarySearchTree #include <iostream> #include <cstdlib> using namespace std; class BinarySearchTree { private: struct tree_node { tree_node* left; tree_node* right; ints data; }; tree_node* root; public: BinarySearchTree() { root = NULL; } bool isEmpty() const { return root==NULL; } void print_inorder(); void inorder(tree_node*); void print_preorder(); void preorder(tree_node*); void print_postorder(); void postorder(tree_node*); void insert(int); void remove(int); }; // Smaller elements go left // larger elements go right void BinarySearchTree::insert(int d) { tree_node* t = new tree_node; tree_node* parent; t->data = d; t->left = NULL; SCITS, KNR 84

Department of CSE

ADSA Lab Manual

t->right = NULL; parent = NULL; // is this a new tree? if(isEmpty()) root = t; else { //Note: ALL insertions are as leaf nodes tree_node* curr; curr = root; // Find the Node's parent while(curr) { parent = curr; if(t->data > curr->data) curr = curr->right; else curr = curr->left; } if(t->data < parent->data) parent->left = t; else parent->right = t;

} }

void BinarySearchTree::remove(int d) { //Locate the element bool found = false; if(isEmpty()) { cout<<" This Tree is empty! "<<endl; return; } tree_node* curr; tree_node* parent; curr = root; while(curr != NULL) { if(curr->data == d) { found = true; break; } else { parent = curr; SCITS, KNR 85

Department of CSE

ADSA Lab Manual

if(d>curr->data) curr = curr->right; else curr = curr->left; } if(!found) }

{ cout<<" Data not found! "<<endl; return;

} // 3 cases : // 1. We're removing a leaf node // 2. We're removing a node with a single child // 3. we're removing a node with 2 children // Node with single child if((curr->left == NULL && curr->right != NULL)|| (curr->left != NULL && curr->right == NULL)) { if(curr->left == NULL && curr->right != NULL) { if(parent->left == curr) { parent->left = curr->right; delete curr; } else { parent->right = curr->right; delete curr; } } else // left child present, no right child { if(parent->left == curr) { parent->left = curr->left; delete curr; } else { parent->right = curr->left; delete curr; } } SCITS, KNR 86

Department of CSE

ADSA Lab Manual

return; } //We're looking at a leaf node if( curr->left == NULL && curr->right == NULL) if(parent->left == curr) parent->left = NULL; else parent->right = NULL; delete curr; return; } //Node with 2 children // replace node with smallest value in right subtree if (curr->left != NULL && curr->right != NULL) { tree_node* chkr; chkr = curr->right; if((chkr->left == NULL) && (chkr->right == NULL)) { curr = chkr; delete chkr; curr->right = NULL; } else // right child has children { //if the node's right child has a left child // Move all the way down left to locate smallest element if((curr->right)->left != NULL) { tree_node* lcurr; tree_node* lcurrp; lcurrp = curr->right; lcurr = (curr->right)->left; while(lcurr->left != NULL) { lcurrp = lcurr; lcurr = lcurr->left; } delete lcurr; lcurrp->left = NULL; } else SCITS, KNR 87

curr->data = lcurr->data;

Department of CSE

ADSA Lab Manual

tree_node* tmp; tmp = curr->right; curr->data = tmp->data; delete tmp; curr->right = tmp->right;

} } } } void BinarySearchTree::print_inorder() { inorder(root); } void BinarySearchTree::inorder(tree_node* p) { if(p != NULL) { if(p->left) inorder(p->left); cout<<" "<<p->data<<" "; if(p->right) inorder(p->right); } else return; } void BinarySearchTree::print_preorder() { preorder(root); } void BinarySearchTree::preorder(tree_node* p) { if(p != NULL) { cout<<" "<<p->data<<" "; if(p->left) preorder(p->left); if(p->right) preorder(p->right); } else return; } SCITS, KNR 88 return;

Department of CSE

ADSA Lab Manual

void BinarySearchTree::print_postorder() { postorder(root); } void BinarySearchTree::postorder(tree_node* p) { if(p != NULL) { if(p->left) postorder(p->left); if(p->right) postorder(p->right); cout<<" "<<p->data<<" "; } else return; } int main() { BinarySearchTree b; int ch,tmp,tmp1; while(1) { cout<<endl<<endl; cout<<" Binary Search Tree Operations "<<endl; cout<<" ----------------------------- "<<endl; cout<<" 1. Insertion/Creation "<<endl; cout<<" 2. In-Order Traversal "<<endl; cout<<" 3. Pre-Order Traversal "<<endl; cout<<" 4. Post-Order Traversal "<<endl; cout<<" 5. Removal "<<endl; cout<<" 6. Exit "<<endl; cout<<" Enter your choice : "; cin>>ch; switch(ch) { case 1 : cout<<" Enter Number to be inserted : "; cin>>tmp; b.insert(tmp); break; case 2 : cout<<endl; cout<<" In-Order Traversal "<<endl; cout<<" -------------------"<<endl; b.print_inorder(); break; case 3 : cout<<endl; cout<<" Pre-Order Traversal "<<endl; SCITS, KNR 89

Department of CSE

ADSA Lab Manual

} } }

cout<<" -------------------"<<endl; b.print_preorder(); break; case 4 : cout<<endl; cout<<" Post-Order Traversal "<<endl; cout<<" --------------------"<<endl; b.print_postorder(); break; case 5 : cout<<" Enter data to be deleted : "; cin>>tmp1; b.remove(tmp1); break; case 6 : system("pause"); return 0; break;

#################################################################### Execution: Step 1: Click Alt+F9 to compile the program. Step 2: Click Ctrl+F9 to run the program.

SCITS, KNR

90

Vous aimerez peut-être aussi