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

CS255 Data Structure Lab Manual

This document provides information about a data structures lab course including prerequisites, course description, objectives, outcomes, evaluation plan, and course plan. The course focuses on practical implementation of data structures like arrays, linked lists, stacks, queues, trees, and graphs using C++. The document also includes examples of array and recursive function implementations, as well as explanations and a sample problem for linked lists. Students will be evaluated based on quizzes, assignments, participation, and a final exam. The course will cover various data structures over 12 weeks based on the topics outlined in the course plan.

Uploaded by

Jagadeesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
426 views

CS255 Data Structure Lab Manual

This document provides information about a data structures lab course including prerequisites, course description, objectives, outcomes, evaluation plan, and course plan. The course focuses on practical implementation of data structures like arrays, linked lists, stacks, queues, trees, and graphs using C++. The document also includes examples of array and recursive function implementations, as well as explanations and a sample problem for linked lists. Students will be evaluated based on quizzes, assignments, participation, and a final exam. The course will cover various data structures over 12 weeks based on the topics outlined in the course plan.

Uploaded by

Jagadeesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Data Structures Lab Manual

2012

Data Structure Lab


Yarmouk University
Faculty of Information Technology and Computer
Sciences
Computer Science Department

CS Department Faculty of IT Yarmouk University

Page 1

Data Structures Lab Manual

2012

CS 255: Data Structure Lab syllabus


Prerequisites and Credits:
CS 117. 1 Credit hour.
Course Description:
This course concentrates on the practical part of the course of Data Structure with
OOP underC++ Environment. This course allows students to understand practically
the Logical andphysical representation of data, algorithms, complexity and efficiency,
data Structure operations, dense lists, and matrix representations, linked lists and their
Different variations, string storage representation and manipulation, queues and stacks
And their applications, tree structures and their different variations, graphs and
Networks , sorting techniques, searching techniques

Course Objectives:
1. Extend programming ability using an object oriented language.
2. Analyze algorithms to determine time and space complexity.
3. Build and manipulate linear and non-linear data structures, including stacks,
queues, linked lists, trees, and graphs.
4. Sort, search, and merge data.
5. Choose the appropriate data structure to use in solving typical computer
science problems.

Learning Outcomes:
After Completing this course the student must demonstrate the Knowledge and
ability to:
1. Demonstrate the application of software engineering principles in design, coding ,
and testing of large programs.
2. To introduce students to essential data structures such as linked lists, stacks,
queues, trees, and graphs. This introduction emphasizes the specification of each
structure as an abstract data type before discussing implementations and application
of the structure.
3. Make students aware of the importance of object oriented methods in
developing software.
4. Student must know the systematic approach to study algorithms , by focuses first
on understanding the action of the algorithm then analyzing it.

Evaluation Plan:
Students will be evaluated based on the following criteria:
Quizzes after finishing each lab subject
60%
Assignment, attendance, participation
10%
Final Lab Exam
30%

Course Plan
CS Department Faculty of IT Yarmouk University

Page 2

Data Structures Lab Manual


Weeks

2012
Subjects and Contents

Week 1

Array (Static data structure)

Week 2

array creation and implementation


Passing to function
Revision
Revision for C++ statements (reading, writing, control structure and
functions)

Week 3

Recursion
Design a recursive functions.

Week 4

Dynamic Array

Week 5

Creation
Passing to function
Insertion Implementation
Delete Implementation
Search Implementation
Sort Implementation
Separation implementation
Merge Implementation
Linked list

Week 6

Creation
Passing to function
Insertion Implementation
Delete Implementation
Search Implementation
Sort Implementation
Double linked list

Week 7

Stack

Creation
Passing to function
Insertion Implementation
Delete Implementation
Search Implementation
Sort Implementation
Separation implementation
Merge Implementation
ADT (array implementation)

Implementing basic operation of stack ( push, pop ) using array


implementation
Week 8

Stack ADT (linked list implementation)

CS Department Faculty of IT Yarmouk University

Page 3

Data Structures Lab Manual

2012

Implementing basic operation of stack ( push, pop ) using linked list


implementation
Week 9

queue ADT

(array implementation)

Implementing basic operation of Queue ( Enqueue, Dequeue ) using array


implementation
Week 10

queue ADT (linked list implementation)


Implementing basic operation of Queue (Enqueue, Dequeue) using linked list
implementation

Week 11

Binary tree
Implement Binary tree traversal methods : Preorder, In-order, Postordered
traversal. Recursive Algorithms for above mentioned
Traversal methods.

Week 12

Binary Search tree


Implementing Binary search tree operation ( search ,addition, deletion).

GOOD LUCK!!!

CS Department Faculty of IT Yarmouk University

Page 4

Data Structures Lab Manual

2012

Array
AIM:To write a program that implements the basic operations of the
Array in C++.
Array
An array is a series of elements of the same type placed in contiguous memory
locations that can be individually referenced by adding an index to a unique identifier.
For example, we can store 5 values of type int in an array without having to declare 5
different variables, each one with a different identifier. Instead of that, using an array
we can store 5 different values of the same type, with a unique identifier.

Lab Question:
Write a program that computes the Summation of Array Values.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

int main ()
{
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}

Output:12206
Excersise1:
Write A c++ Program That checks if a given Array is a Palindrome.
palindrome is a number that remains the same when its digits are reversed. Like
16461, for example
Excersise2:
Write A c++ Program Which Call A Function Which Sort The Given Array.

CS Department Faculty of IT Yarmouk University

Page 5

Data Structures Lab Manual

2012

Dynamic Array
AIM:To write a program that implements a dynamic Array in C++.

Dynamic Array
Is a random access, variable-size list data structure that allows elements to be added
or removed. It is supplied with standard libraries in many modern mainstream
programming languages.

Lab Question:
Write A c++ Program Which Creates And Prints Dynamic Array Of Integer Type.
1. #include<iostream>
2. using namespace std;
3. class array {
4. private:
5. int size;
6. int *ptr;
7. public:
8. array(int s) {
9. size=s;
10. ptr=new int[size];
11. for(int a=0;a<size;a++)
12.
ptr[a]=0;
13. }
14. void read() {
15. for(int a=0;a<size;a++)
16.
cin>>ptr[a];
17. }
18. };
19.
20. void main() {
21. int x;
22. cout<<"Enter The Dynamic Array Size..."<<endl;
23. cin>>x;
24. array a1(x);
25. cout<<"Enter ur array elements.....\n";
26. a1.read();
27. cout<<"ur array elements Are........\n";
28. a1.print();
29. }

Excersises:
1. Write A c++ Program Which Delete By Shift The Median Value Of A Given
Dynamic Array.
2. Write A c++ Program Which Insert By Shift A New Value Before The
Maximum Value Of A Given Dynamic Array.

CS Department Faculty of IT Yarmouk University

Page 6

Data Structures Lab Manual

2012

Recursion /Recursive Functions


AIM:To write a program that implements a recursive functions C++.
Recursion
Recursion is a programming technique that allows the programmer to express
operations in terms of themselves. In C++, this takes the form of a function that calls
itself. A useful way to think of recursive functions is to imagine them as a process
being performed where one of the instructions is to "repeat the process". This makes it
sound very similar to a loop because it repeats the same code, and in some ways it is
similar to looping. On the other hand, recursion makes it easier to express ideas in
which the result of the recursive call is necessary to complete the task. Of course, it
must be possible for the "process" to sometimes be completed without the recursive
call. One simple example is the idea of building a wall that is ten feet high; if I want
to build a ten foot high wall, then I will first build a 9 foot high wall, and then add an
extra foot of bricks. Conceptually, this is like saying the "build wall" function takes a
height and if that height is greater than one, first calls itself to build a lower wall, and
then adds one a foot of bricks.

Lab Question:
Write a Recursive Function To Print Number From Given input down to 0
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

class rec1
{
public:
void printIt( int n ) {
if ( n == 0 ) cout << endl;// base case
else
{ printIt( n - 1 ); // recursive call
cout << n - 1 << ;
}
}
};
void main()
{
rec1 call;
call.printIt(5);
}

Output: 4 3 2 1 0
Excersise: use a recursive function to write a program that performs the following
tasks.
1. Find The Factorial Number For an input n.
2. Check If a Given Array Values Are Palindrome or not.

Linked list ADT


CS Department Faculty of IT Yarmouk University

Page 7

Data Structures Lab Manual

2012

AIM:To write a program that implements the basic operations of the


linked list in C++
Linked List Overview

List is a collection of components, called nodes. Every node (except the last
node) contains the address of the next node. Every node in a linked list has
two components:
1. one to store the relevant information (that is, data)
2. one to store the address, called the link or next , of the next node in the
list.
The address of the first node in the list is stored in a separate location, called
the head or first
The address of the last node in the list is stored in a separate location, called
the tail or last

UML view of basic operation in list

Lab Question:
Write class called node that contain:
CS Department Faculty of IT Yarmouk University

Page 8

Data Structures Lab Manual

2012

data members:
1. data as integer.
2. next as pointer of type node.
3. head as pointer of type node.
4. tail as pointer of type node.
5. current as pointer of type node.
6. count as integer.
The following functions:
1. constructor to initialize data member
2. Function called initializelist to enter values to list until reach to value -1.
3. Function called print to print list.
Then write main to test this class
Answer:

1. class node
2. {
3. private:
4. int data;
5. node *next;
6. node *current,*head,*tail;
7. public:
8. node(){
9.
head=current=tail=next=NULL;
10.
data=0;
11.
}
12.
void initializelist() { //create
13.
head=tail=current=new node;
14.
cin>>current->data;
15.
int x;
16.
cin>>x;
17.
while(x!=-1){
18.
current=new node;
19.
current->data=x;
20.
tail->next=current;
21.
tail=current;
22.
cin>>x;
}
23.
}
24.
void print() { //Print
25.
current=head;
26.
while(current!=tail) {
27.
cout<<current->data<<"\t";
28.
current=current->next;
29.
}
30.
cout<<tail->data<<"\t";
31.
cout<<endl;
32.
}
33.
};
34.
void main(){
35.
node LS;
36.
LS.initializelist();
37.
LS.print();
38.
}

Exercise 1:
Modify class node in Exercise 1 by adding the following:
CS Department Faculty of IT Yarmouk University

Page 9

Data Structures Lab Manual

2012

1. Function called max to return maximum value in the list.


2. Function called length to return number of nodes in list.
3. Function called sort to sort elements of list.

Exercise 2:
Modify class node in Exercise 1 by adding the following:
1. Function called InsertAtBegin to add node at the begging of list.
2. Function called InsertAtEnd to add node at the last of list.
3. Function called Insert to inset new value after specific value in list.
4. Function called DeleteFromBegin to delete node from the begging of list.
5. Function called DeleteFromEnd to delete node from the last of list.
6. Function called Delete to delete maximum value in list.

CS Department Faculty of IT Yarmouk University

Page 10

Data Structures Lab Manual

2012

Double linked list ADT


AIM:To write a program for double linked list implementation .
A doubly linked list overview:
A doubly linked list is a linked list in which every node has a next pointer and a
back pointer. Every node contains the address of the next node (except the last
node), and every node contains the address of the previous node (except the first
node). A doubly linked list can be traversed in either direction

Lab Question:
Write class called node that contain:

data members:
7. data as integer.
8. next as pointer of type node.
9. back as pointer of type node.
10. head as pointer of type node.
11. tail as pointer of type node.
12. current as pointer of type node.

The following functions:


4. constructor to initialize data member
5. Function called initializelist to enter values to list until reach to value -1.
6. Function called print to print list.
Then write main to test this class
Answer:

CS Department Faculty of IT Yarmouk University

Page 11

Data Structures Lab Manual

2012

class node
{
private:
int data;
node *next , *back;
node *current,*head,*tail;
public:
node()
{
head=current=tail=next=NULL;
data=0;
}
void initializelist()//create
{
head=tail=current=new node;
cin>>current->data;
int x;
cin>>x;
while(x!=-1)
{
current=new node;
current->data=x;
head->next=current;
head=current;
cin>>x;
}
}
void print()//Print
{
current=head;
while(current!=tail)
{
cout<<current->data<<"\t";
current=current->next;
}
cout<<tail->data<<"\t";
cout<<endl;
}
};
Exercisevoid
1: main()
{
node
LS;
Modify class node
in Exercise
1 by adding the following:
LS.initializelist();
LS.print();
4. Function
called max to return maximum value in the list.
}

5. Function called length to return number of nodes in list.


6. Function called sort to sort elements of list.
7. Function called reverse to print elements of list in reverse order.

CS Department Faculty of IT Yarmouk University

Page 12

Data Structures Lab Manual

2012

Stack ADT
AIM:To write a program for linked implementation of stack in C++

Stacks Overview
 Stack is data structure in which the elements are added and removed from one
end only; a Last In First Out (LIFO) data structure

UML view of stack:

Lab Question:
Write class called Stack that contains:
data members:
1. size as integer.
2. stack as pointer of type stack.
3. stacktop as pointer of type stack.
The following functions:
1. constructor to initialize data member
2. intializestack to pushing elements to stack.
Then write main to test this class
Answer:

CS Department Faculty of IT Yarmouk University

Page 13

Data Structures Lab Manual

2012

1. class Stack
2. {
3. private:
4. int maxsize;
5. int stacktop;
6. int *stack;
7. public:
8. array_stack(int s=100)
9. {
10.
maxsize=s;
11.
stack=new int[maxsize];
12.
stacktop=0;
13.
}
14.
};

Exercise 1:
Modify class node in Exercise 1 by adding the following:
1. Function Push to add element to stack
2. Function Pop to delete element from stack
3. Function isEmpty to true if stack is empty otherwise return false.
4. Function isFull to true if stack is empty otherwise return false.
5. Function top to retrieve elements at top of stack.
6. separate function called reverse to reverse elements of stack in another stack

CS Department Faculty of IT Yarmouk University

Page 14

Data Structures Lab Manual

2012

Queue ADT
AIM:To write a program for array implementation of queue in C++
QUEUE:
The queue is a data structure that allows use of two ends of it. I mean from one
end of thequeue you can insert the elements and from another end of the queue
you can delete theelements.The Queue can be formally defined as ordered
collection of elements that has two endsnamed as front and rear. From the front
end one can delete the elements and from the rear endone can insert the
elements. The queue is also called as First in First out (FIFO) data structure.
TWO TYPES OF REPRESENTATIONS OF QUEUE
Array Representations
Linked list Representation

Basic operations:
Enqueue(x) : insert item x at the rear
Dequeue() : delete the rear element

CS Department Faculty of IT Yarmouk University

Page 15

Data Structures Lab Manual

2012

Queue ADT Array implementations


AIM: To write a program for linked list implementation of queue
Queue is nothing but the collection of items. Both the ends of the queue are
having their own functionality. All theelements in the queue are stored
sequentially.The two queue ends are front and rear

ENQUEUE OPERATION
1) Get the element to be inserted
2) Check whether the queue is full.
3) If the queue is full
a. we cannot insert an element into the queue.
b. Queue is overflow error occurs.
4) ELSE
a. We may insert the element into the queue.
b. Rear= (rear + 1)%size;
c. queue[rear]= x;

DEQUEUE OPERATION
1) Check whether the queue is Empty.
2) If the queue is empty
a. we cannot delete an element from the queue.
b. Queue is empty error occurs.
3) ELSE
a. we maydelete an element from the queue.
b. x = queue[front];
c. Front = (front +1)%size;
d. Return x

CS Department Faculty of IT Yarmouk University

Page 16

Data Structures Lab Manual

2012

Lab Question:
Write a C++ code to implement enqueue and dequeue using array.
1. # include<iostream.h>
2. # include<conio.h>
3. # define SIZE 20
4. class queue {
5. int a[SIZE];
6. int front;
7. int rear;
8. int count
9. queue();
10.
~queue();
11.
void insert(int i);
12.
void remove();
13.
bool isempty();
14.
bool isfull();
15.
};
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.

queue::queue() {
front=0; rear=0; count =0;
}
void queue::insert(int i) {
if(isfull())
{
cout<<" ** Queue is FULL !!! No insertion
return;
}
a[rear] = i;
rear = (rear+1)%size;
}
void queue::remove() {
if(isempty())
cout<<"Queue Empty !!!";
else
front = (front+1)%size
}
bool queue::isempty()
{
return (count == 0) }
bool queue::isfull()
{
return (count == size) }

38.
39.
40.
41.
42.
43.
44.
45.
46.

void main() {
queue q;
q.insert(1);
q.insert(2);
q.remove();
q.remove();
q.remove();
getch();
}

**";

CS Department Faculty of IT Yarmouk University

Page 17

Data Structures Lab Manual

2012

Queue ADT linked list implementations


AIM: To write a program for linked list implementation of queue
The main advantage in linked representation is that we need not have to worry about
sizeof the queue. As in linked organization we can create as many nodes as we want
so there will not be a queue full condition at all. The queue using linked list will be
very much similar to a linkedlist. The only difference between the two is in queue, the
left most nodes is called front node andthe right most node is called rear node. We are
only allowed to remove an item from the front node. On the other hand, we only can
insert new items at the rear of the list only.

ENQUEUE OPERATION
1) Get the element to be inserted
2) Create a new node.
Node * p;
P = ( node * ) mallloc (size of ( node ) );
P -> data = x;
P -> next = NULL
3) If ( rear ! = NULL)
Rear -> next = p;
Rear = p;
4) Else
Front = p;
Rear = p;

DEQUEUE OPERATION
1) Check the condition whether the queue is empty or not.
2) If ( front = = NULL && rear = = NULL)
//we cannot delete element from the queue.
Cout << Queue underflow
3) ELSE
//We can delete element from it.
If (front == rear) //Check whether both the ends are equal.
Front = rear = NULL;
ELSE
Node * p;
P = front;
Front = front-> next
Delete (p)

CS Department Faculty of IT Yarmouk University

Page 18

Data Structures Lab Manual

2012

Lab Question:Write a C++ code to implement enqueue and dequeue using array.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.

#include<iostream>
#include<cstdlib>
using namespace std;
struct node{
int info;
struct node *next;
};
class Queue{
private:
node *rear;
node *front;
public:
Queue();
void enqueue();
void dequeue();
void display();
};
Queue::Queue(){
rear = NULL;
front = NULL;
}
void Queue::enqueue(){
int data;
node *temp = new node;
cout<<"Enter the data to enqueue: ";
cin>>data;
temp->info = data;
temp->next = NULL;
if(front == NULL){
front = temp;
}else{
rear->next = temp;
}
rear = temp;
}
void Queue::dequeue(){
node *temp = new node;
if(front == NULL){
cout<<"\nQueue is Emtpty\n";
}else{
temp = front;
front = front->next;
cout<<"The data Dequeued is "<<temp->info;
delete temp;
}
}
void Queue::display(){
node *p = new node;
p = front;
if(front == NULL){

CS Department Faculty of IT Yarmouk University

Page 19

Data Structures Lab Manual


51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.

2012

cout<<"\nNothing to Display\n";
}else{
while(p!=NULL){
cout<<endl<<p->info;
p = p->next;
}
}
}
int main(){
Queue queue;
int choice;
while(true){
cout<<"\n1.Enqueue\n2. Dequeue\n3. Display\n 4.Quit";
cout<<"\nEnter your choice: ";
cin>>choice;
switch(choice){
case 1:
queue.enqueue();
break;
case 2:
queue.dequeue();
break;
case 3:
queue.display();
break;
case 4:
exit(0);
break;
default:
cout<<"\nInvalid Input. Try again! \n";
break;
}
}
return 0;
}

CS Department Faculty of IT Yarmouk University

Page 20

Data Structures Lab Manual

2012

Binary Tree
Aim: Implement the Binary Tree Traversal
Procedure:
1) Make the structure of Binary Tree Traversal for integer numbers.
struct node {
int data;
struct node* left;
struct node* right;
}
2) implement inorder(), preorder() and postorder() traversal for it.
Preorder
1) Visit the root.
2) Traverse the left subtree.
3) Traverse the right subtree.
Inorder
1) Traverse the left subtree.
2) Visit the root.
3) Traverse the right subtree.
Postorder
1) Traverse the left subtree.
2) Traverse the right subtree.
3) Visit the root.

Lab Question:Write a C++ code to implement enqueue and dequeue using array.
1. #include <iostream>
2. #include <cstdlib>
3. using namespace std;
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

class BinaryTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
int data;
};
tree_node* root;

14.
15.
16.
17.
18.

public:
BinaryTree()
{
root = NULL;
}

CS Department Faculty of IT Yarmouk University

Page 21

Data Structures Lab Manual

19.
20.
21.
22.
23.
24.
25.
26.
27.
28.

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);
};

29.
30.
31.
32.

void BinaryTree::print_inorder()
{
inorder(root);
}

33.
34.
35.
36.
37.
38.
39.
40.
41.
42.

void BinaryTree::inorder(tree_node* p)
{
if(p != NULL)
{
if(p->left) inorder(p->left);
cout<<" "<<p->data<<" ";
if(p->right) inorder(p->right);
}
else return;
}

43.
44.
45.
46.

void BinaryTree::print_preorder()
{
preorder(root);
}

47.
48.
49.
50.
51.
52.
53.
54.
55.
56.

void BinaryTree::preorder(tree_node* p)
{
if(p != NULL)
{
cout<<" "<<p->data<<" ";
if(p->left) preorder(p->left);
if(p->right) preorder(p->right);
}
else return;
}

57.
58.
59.
60.

void BinaryTree::print_postorder()
{
postorder(root);
}

2012

61. void BinaryTree::postorder(tree_node* p)


62. {
63. if(p != NULL)
CS Department Faculty of IT Yarmouk University

Page 22

Data Structures Lab Manual


64.
65.
66.
67.
68.
69.
70.

2012

{
if(p->left) postorder(p->left);
if(p->right) postorder(p->right);
cout<<" "<<p->data<<" ";
}
else return;
}

71. int main()


72. {
73. BinaryTree b;
74. int ch,tmp,tmp1;
75. while(1)
76. {
77. cout<<endl<<endl;
78. cout<<" Binary Tree Operations "<<endl;
79. cout<<" ----------------------------- "<<endl;
80. cout<<" 1. In-Order Traversal "<<endl;
81. cout<<" 2. Pre-Order Traversal "<<endl;
82. cout<<" 3. Post-Order Traversal "<<endl;
83. cout<<" 4. Exit "<<endl;
84. cout<<" Enter your choice : ";
85. cin>>ch;
86. switch(ch)
87. {
88. case 1 : cout<<endl;
89. cout<<" In-Order Traversal "<<endl;
90. cout<<" -------------------"<<endl;
91. b.print_inorder();
92. break;
93. case 2 : cout<<endl;
94. cout<<" Pre-Order Traversal "<<endl;
95. cout<<" -------------------"<<endl;
96. b.print_preorder();
97. break;
98. case 3 : cout<<endl;
99. cout<<" Post-Order Traversal "<<endl;
100.
cout<<" --------------------"<<endl;
101.
b.print_postorder();
102.
break;
103.
case 4 :
a. return 0;
104.
105.
106.

}
}
}

CS Department Faculty of IT Yarmouk University

Page 23

Data Structures Lab Manual

2012

Binary Search Tree


AIM: To write a program that implement the basic operations of a Binary
search tree.
A binary search tree is a binary tree in which the data in the nodes is ordered in the
following way. Starting at any given node, the data in any nodes of its left subtree
must all be less than the item in the given node, and the data in any nodes of its right
subtree must be greater than or equal to the data in the given node. Of course, all of
this implies that the data items can be ordered by some sort of less than relationship.
For numbers this can obviously be done. For strings, alphabetical ordering is often
used. For records of data, a comparison based on a particular field (the key field) is
often used.
A binary search tree can be traversed in same methods that are used to traverse any
binary tree, inorder, preorder, and postorder.
BST Basic operations:

Insertion, Deletion

Insertion:
To insert a new node into the BST

Proceed down the tree as you would with a find

insert X at the last spot on the path traversed

Deletion:
 Case 1: the node is a leaf
 Delete it immediately
 Case 2: the node has one child
 Adjust a pointer from the parent to bypass that node
 Case 3: the node has 2 children
 Replace the key of that node with the minimum element at the right
subtree
 Delete that minimum element
 Has either no child or onlyone child because if it has a left
child, that left child would be smaller and would have been
chosen. So invoke case 1 or 2.
CS Department Faculty of IT Yarmouk University

Page 24

Data Structures Lab Manual

2012

Lab Question:Write a C++ code to implement binary search tree insertion and
deletion operations.
1. #include <iostream>
2. #include <cstdlib>
3. using namespace std;
4. class BinarySearchTree
5. {
6. private:
7. struct tree_node
8. {
9. tree_node* left;
10. tree_node* right;
11. int data;
12. };
13. tree_node* root;
14. public:
15. BinarySearchTree()
16. {
17. root = NULL;
18. }
19. bool isEmpty() const { return root==NULL; }
20. void insert(int);
21. void remove(int);
22. };

23. void BinarySearchTree::insert(int d)


24. {
25. tree_node* t = new tree_node;
26. tree_node* parent;
27. t->data = d;
28. t->left = NULL;
29. t->right = NULL;
30. parent = NULL;
31. // is this a new tree?
32. if(isEmpty()) root = t;
33. else
34. {
35. //Note: ALL insertions are as leaf nodes
36. tree_node* curr;
37. curr = root;
38. // Find the Node's parent
39. while(curr)
40. {
41. parent = curr;
CS Department Faculty of IT Yarmouk University

Page 25

Data Structures Lab Manual

2012

42. if(t->data > curr->data) curr = curr->right;


43. else curr = curr->left;
44. }
45. if(t->data < parent->data)
46. parent->left = t;
47. else
48. parent->right = t;
49. }
50. }
51. void BinarySearchTree::remove(int d)
52. {
53. //Locate the element
54. bool found = false;
55. if(isEmpty())
56. {
57. cout<<" This Tree is empty! "<<endl;
58. return;
59. }
60. tree_node* curr;
61. tree_node* parent;
62. curr = root;
63. while(curr != NULL)
64. {
65. if(curr->data == d)
66. {
67. found = true;
68. break;
69. }
70. else
71. {
72. parent = curr;
73. if(d>curr->data) curr = curr->right;
74. else curr = curr->left;
75. }
76. }
77. if(!found)
i. {
78. cout<<" Data not found! "<<endl;
79. return;
80. }

i. // 3 cases :
81. // 1. We're removing a leaf node
82. // 2. We're removing a node with a single child
83. // 3. we're removing a node with 2 children
CS Department Faculty of IT Yarmouk University

Page 26

Data Structures Lab Manual

2012

84. // Node with single child


85. if((curr->left == NULL && curr->right != NULL)|| (curr->left != NULL
86. && curr->right == NULL))
87. {
88. if(curr->left == NULL && curr->right != NULL)
89. {
90. if(parent->left == curr)
91. {
92. parent->left = curr->right;
93. delete curr;
94. }
95. else
96. {
97. parent->right = curr->right;
98. delete curr;
99. }
100.
}
else // left child present, no right child
101.
{
102.
103.
if(parent->left == curr)
{
104.
parent->left = curr->left;
105.
106.
delete curr;
}
107.
108.
else
{
109.
110.
parent->right = curr->left;
delete curr;
111.
112.
}
113.
}
114.
return;
115.
}
//We're looking at a leaf node
if( curr->left == NULL && curr->right == NULL)
116.
117.
118.

119.

{
if(parent->left == curr) parent->left = NULL;
else parent->right = NULL;
a. delete curr;
b. return;
}

120.
121.
122.
123.
124.
125.

//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;

CS Department Faculty of IT Yarmouk University

Page 27

Data Structures Lab Manual


126.
127.
128.
129.
130.
131.
132.
133.
134.
135.

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

136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.

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;
}
curr->data = lcurr->data;
delete lcurr;
lcurrp->left = NULL;
}
else
{
tree_node* tmp;
tmp = curr->right;
curr->data = tmp->data;
curr->right = tmp->right;
delete tmp;
}
}
return;
}
}

2012

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. Removal "<<endl;

CS Department Faculty of IT Yarmouk University

Page 28

Data Structures Lab Manual


175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.

2012

cout<<" 3. 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<<" Enter data to be deleted : ";
cin>>tmp1;
b.remove(tmp1);
break;
case 3 :
return 0;
}
}
}

CS Department Faculty of IT Yarmouk University

Page 29

You might also like