C++ Programs Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

1a) Write a program to generate the foolowing string

1
1 2
1 2 3
1 2 3 4

Program :-

#include<iostream>
#include<conio.h>
void main()
{
int i,j,n;
cout<<"enter the size of rows:"<<endl;
cin>>n;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
cout<<j;
}
cout<<endl;
}
getch();
}

Output:-
enter the size of rows:
4
1
12
123
1234

1b) Write a program which uses function to swap two integers and two
float numbers by using reference variable
Program :-
#include<iostream>
#include<conio.h>

void swap(int &x,int &y,float &p,float &q);


void main()
{
int a,b;
float p,q;
cout<<"Enter a,b,p,q"<<endl;
cin>>a>>b>>p>>q;
swap(a,b,p,q);
getch();
}
void swap(int &x,int &y,float &p,float &q)
{
int temp;
float temp1;
temp=x;
x=y;
y=temp;
temp1=p;
p=q;
q=temp1;
cout<<"Integers after swapping are:"<<endl<<x<<endl<<y<<endl;
cout<<"Float numbers after swapping are:"<<endl<<p<<endl<<q<<endl;
}

Output:-
Enter a,b,p,q
2
3
4.5
5.5
Integers after swapping are:
3
2
Float numbers after swapping are:
5.5
4.5

1c) Write a program that demonstrate default arguments.

Program :-

#include<iostream>
#include<conio.h>
void display(char = '*',int = 3);
void main()
{
int count=5;
cout<<"No argument passed:";
display();
cout<<"First argument passed:";
display('#');
cout<<"Both argument passed:";
display('$',count);
getch();
}
void display(char c,int count)
{
for(int i=1;i<=count;i++)
{
cout<<c;
}
cout<<endl;
}
Output:-
No argument passed:***
First argument passed:###
Both argument passed:$$$$$

2a) Write a program illustrating class declarations , defitions and class


member.
Program:-
#include<iostream>
#include<conio.h>
class student
{
private: int sno;
char sname[20];
public: void getdata()
{
cout<<"enter the students details:"<<endl;
cin>>sno>>sname;
}
void display()
{
cout<<"sno is:"<<sno<<endl<<"sname is:"<<sname<<endl;
}

public: void getdata();


public: void display();

};
void getdata()
{
cout<<"enter the students details:"<<endl;
cin>>sno>>sname;
}
void display()
{
cout<<"sno is:"<<sno<<endl<<"sname is:"<<sname<<endl;
}

void main()
{
student s1;
s1.getdata();
s1.display();
getch();
}
Output:-
enter the students details:
62
nitya
sno is: 12
sname is: nitya
2b) Write a program to illustrate default constructor, parameterized
constructor and copy constructor for a class
Program:-
#include<iostream>
#include<conio.h>
class test
{
private:int a,b;
public:test()
{
cout<<"enter the values a and b:"<<endl;
cin>>a>>b;
}
void display()
{
cout<<"a value is:"<<a<<endl;
cout<<"b value is:"<<b<<endl;
}
test(int a, int b)
{
this->a=a;
this->b=b;
}
void displaydata()
{
cout<<"sum of a and b is :"<<a+b<<endl;
cout<<"product of a and b is :"<<a*b<<endl;
}
test(test &t)
{
a=t.a;
b=t.b;
}
};
int main()
{
test t;
t.display();
test t1(10,20);
test t2=t1;
t1.display();
t2.display();
t1.displaydata();
getch();
return 0;
}

#include<iostream>
#include<conio.h>
using namespace std;
class sample
{
private:int x;
public:sample(int x)
{
this->x=x;
cout<<"constructor"<<x<<"is called"<<endl;
}
~sample()
{
cout<<"destructor"<<x<<"is called"<<endl;
}
};
int main()
{
sample s1(2),s2(3);
{
sample s3(4),s4(5);
}
sample s5(6),s6(7);
getch();
return 0;
}

Output:-

1)
enter the values a and b:
2
3
a value is:2
b value is:3
a value is:10
b value is:20
a value is:10
b value is:20
sum of a and b is :30
product of a and b is :200

2)
constructor2is called
constructor3is called
constructor4is called
constructor5is called
destructor5is called
destructor4is called
constructor6is called
constructor7is called
destructor7is called
destructor6is called
destructor3is called
destructor2is called

3a)Write a program that illstrates the following forms of


inheritence:singlr,mutliple,mutlilevel,hierarchial
Progarm:-
#include<iostream>
#include<conio.h>
using namespace std;
class A
{
public:int sno,age;
char name[20];
public:void get()
{
cout<<"Enter the student details :"<<endl;
cin>>sno>>age>>name;
}
};
class B : public A //Single inheritence
{
public:void put()
{
cout<<"Student details are:"<<endl;
cout<<"sno is:"<<sno<<endl<<"age is:"<<age<<endl<<"name
is:"<<name<<endl;
}
};
class C : public B //Multilevel inheritence
{
private:int m1,m2,m3;
public:void getdata()
{
cout<<"enter the details of the marks"<<endl;
cin>>m1>>m2>>m3;
}
void putdata()
{
cout<<"students marks are:"<<endl<<m1<<endl<<m2<<endl<<m3;
}
};
int main()
{
C obj;
obj.get();
obj.getdata();
obj.put();
obj.putdata();
getch();
return 0;
}

// Multiple inheritence

#include<iostream>
#include<conio.h>
using namespace std;
class A
{
public:int a;
public:void get(int n)
{
a=n;
}
};
class B
{
public:int b;
public:void getdata(int n)
{
b=n;
}
};
class C : public A,public B
{
public:void display()
{
cout<<"The value of a is"<<a<<endl;
cout<<"The value of b is"<<b<<endl;
cout<<"Additon of a and b is :"<<a+b<<endl;
}
};
int main()
{
C obj;
obj.get(10);
obj.getdata(20);
obj.display();
getch();
return 0;
}

// Hierarchial inheritence

#include<iostream>
#include<conio.h>
using namespace std;
class A
{
public:int x,y;
void get()
{
cout<<"Enter x and y:"<<endl;
cin>>x>>y;
}
void put()
{
cout<<"x value is"<<x<<endl;
cout<<"y value is"<<y<<endl;
}
};
class B : public A
{
public:void sum()
{
cout<<"sum of x and y is :"<<x+y;
}
};
class C : public A
{
public:void product()
{
cout<<"Product of x and y is:"<<x*y;
}
};
int main()
{
B obj;
C obj1;
obj.get();
obj.sum();
obj1.get();
obj1.product();
getch();
return 0;
}

Output :-

1)
Enter the student details :
62
19
vinay
enter the details of the marks
98
99
96
Student details are:
sno is:62
age is:19
name is:vinay
students marks are:
98
99
96

2)
The value of a is10
The value of b is20
Additon of a and b is :30

3)
Enter x and y:
6
2
sum of x and y is :8
Enter x and y:
6
2
Product of x and y is:12

3b) Write a program and create multiple objects for the class and observe
the older in which constructor and destructor are called

Program:-

#include<iostream>
#include<conio.h>
using namespace std;
class sample
{
private:int x;
public:sample(int x)
{
this->x=x;
cout<<"constructor"<<x<<"is called"<<endl;
}
~sample()
{
cout<<"destructor"<<x<<"is called"<<endl;
}
};
int main()
{
sample s1(2),s2(3);
{
sample s3(4),s4(5);
}
sample s5(6),s6(7);
getch();
return 0;
}

Output:-

constructor2is called
constructor3is called
constructor4is called
constructor5is called
destructor5is called
destructor4is called
constructor6is called
constructor7is called
destructor7is called
destructor6is called
destructor3is called
destructor2is called

4a) Write a program to use pointers for both base and derived classes and
calls the memmber functions
Program :-

#include<iostream>
#include<conio.h>
using namespace std;
class base
{
public:int a,b;
void add()
{
a=10;
b=20;
cout<<"addition of a and b is :"<<a+b<<endl;
}
};
class derived : public base
{
public:int c,d;
void mul()
{
c=3;
d=4;
cout<<"multiplication of c and d is :"<<c*d;
}
};
int main()
{
base *bptr;
base bobj;
bptr=&bobj;
bptr->add();
derived *dptr;
derived dobj;
dptr=&dobj;
dptr->mul();
getch();
return 0;
}

Output :-

addition of a and b is :30


multiplication of c and d is :12

4b) Write a program that demonstrate function overloading and operator


overloading

Progrom :-

#include<iostream>
#include<conio.h>
using namespace std;
class test
{
private:int a,b;
public:void add(int a,int b)
{
cout<<"sum="<<a+b<<endl;
}
void add(double a,double b,double c)
{
cout<<"sum="<<a+b+c<<endl;
}
};
int main()
{
test t;
t.add(10,5);
t.add(6.5,5.5,4.5);
getch();
return 0;
}

2) operator overload

Program :-

#include<iostream>
#include<conio.h>
using namespace std;
class complex
{
private:int real,img;
public:void get()
{
cin>>real>>img;
}
void show()
{
cout<<real<<"+i"<<img<<endl;
}
complex operator +(complex obj)
{
complex c;
c.real=real+obj.real;
c.img=img+obj.img;
return c;
}
};
int main()
{
complex a,b,c;
cout<<"enter the first complex number:"<<endl;
a.get();
cout<<"enter the second complex number:"<<endl;
b.get();
c=a+b;
c.show();
getch();
return 0;
}

Output:-

1)
sum=15
sum=16.5

2)
enter the first complex number:
8
7
enter the second complex number:
7
8
15+i15

5a) Write a program that demonstrate friend function and inline function

Program :-

#include<iostream>
#include<conio.h>
using namespace std;
class sample
{
private:int a,b;
public:void get()
{
cout<<"enter the values of a and b:";
cin>>a>>b;
}
friend void display(sample obj);
};
void display(sample obj)
{
cout<<"a value is:"<<obj.a<<endl;
cout<<"b value is:"<<obj.b<<endl;
}
int grt(int x,int y,int z)
{
int g;
return((g=(x>y?x:y))>z?g:z);
}

int main()
{
sample s;
int p,q,r;
s.get();
display(s);
cout<<"enter p,q,r"<<endl;
cin>>p>>q>>r;
int d=grt(p,q,r);
cout<<"greatest num:"<<d;
getch();
return 0;
}

Output:-

enter the values of a and b:12


32
a value is:12
b value is:32
enter p,q,r
4
6
8
greatest num:8

5b) Write a program to demonstrate the virtual and static functions

Program:-

#include<iostream>
#include<conio.h>
using namespace std;
class base
{
public:virtual void print()
{
cout<<"print base class"<<endl;
}
void show()
{
cout<<"show base class"<<endl;
}
};
class derived : public base
{
public:void print()
{
cout<<"print derived class"<<endl;
}
void show()
{
cout<<"show derived class"<<endl;
}
};
class test
{
private:int a;
static int c;
public:void get()
{
a=10;
a++;
c++;
}
void display()
{
cout<<"a:"<<a<<endl;
cout<<"c:"<<c<<endl;
}
};
int test :: c=100;
int main()
{
base *bptr;
derived d;
bptr =&d;
bptr->print();
bptr->show();
test t1,t2;
t1.get();
t1.display();
t2.get();
t2.display();
getch();
return 0;
}

Output:-

print derived class


show base class
a:11
c:101
a:11
c:102

6a) Write a program which uses the concept of pass and return objects of
functions

Program:-

// pass

#include<iostream>
#include<conio.h>
using namespace std;
class Student {

public:
double marks;

// constructor to initialize marks


Student(double m) {
marks = m;
}
};

// function that has objects as parameters


void calculateAverage(Student s1, Student s2) {

// calculate the average of marks of s1 and s2


double average = (s1.marks + s2.marks) / 2;

cout << "Average Marks = " << average << endl;

int main() {
Student student1(88.0), student2(56.0);

// pass the objects as arguments


calculateAverage(student1, student2);

return 0;
}

// return

#include <iostream>
using namespace std;

class Student {
public:
double marks1, marks2;
};

// function that returns object of Student

Student createStudent() {
Student student;

// Initialize member variables of Student


student.marks1 = 96.5;
student.marks2 = 75.0;

// print member variables of Student


cout << "Marks 1 = " << student.marks1 << endl;
cout << "Marks 2 = " << student.marks2 << endl;

return student;
}

int main() {
Student student1;

// Call function
student1 = createStudent();
return 0;
}

Output:-

1)
Average Marks = 72

2)
Marks 1 = 96.5
Marks 2 = 75

6b) Write a program to create an array of objects

Program:-

#include<iostream>
#include<conio.h>
using namespace std;
class student
{
private:int sno;
char sname[20];
public:void get()
{
cout<<"enter details:"<<endl;
cin>>sno>>sname;
}
void put()
{
cout<<"sno:"<<sno<<endl<<"sname:"<<sname<<endl;
}
};
int main()
{
student s[5];
int i;
for (i=0;i<=2;i++)
{
s[i].get();
s[i].put();
}
getch();
return 0;
}

Output:-

enter details:
62
vinay
sno:62
sname:vinay
enter details:
1
akash
sno:1
sname:akash
enter details:
2
akhil
sno:2
sname:akhil

7a)Write a program that handles exception using try,catch,throw

Program :-

#include<iostream>
using namespace std;
double division(int a,int b)
{
if(b==0)
{
throw "Division by zero!";
}
return(a/b);
}
int main()
{
int x=20;
int y=0;
double z=0;
try
{
z=division(x,y);
cout<<z<<endl;
}
catch(const char* msg)
{
cerr<<msg<<endl;
}
return 0;
}

Output:-

Division by zero!

7b)Write a program to demonstrate to catch all the exceptions

Program:-

#include <iostream>
using namespace std;
int main()
{
int x = 1;
char a = 'a';
try{
if(x == 0){
throw x;;
}
if(a == 'a'){
throw a;
}
}
catch(...){
cout << "Exception Caught";
}
return 0;
}

Output:-

Exception Caught

8)Write a program to demonstrate user defined exceptions

Program :-

#include <iostream>
#include <exception>
using namespace std;
class MyException : public exception{
public:
const char * what() const throw()
{
return "Attempted to divide by zero!\n";
}
};
int main()
{
try
{
int x, y;
cout << "Enter the two numbers : \n";
cin >> x >> y;
if (y == 0)
{
MyException z;
throw z;
}
else
{
cout << "x / y = " << x/y << endl;
}
}
catch(exception& e)
{
cout << e.what();
}
}

Output:-

Enter the two numbers :


30
0
Attempted to divide by zero!

9) Write a program to create a generic template for adding 2 integers and


float numbers and make use of the template to perform addition

Program :-

#include<iostream>
#include<conio.h>
using namespace std;
template<class t>class test
{
private:t a,b;
public:void get(t x,t y)
{
a=x;
b=y;
}
void display()
{
cout<<"a:"<<a<<endl<<"b:"<<b<<endl<<"sum:"<<a+b<<endl;
}
};
int main()
{
test <int> i;
i.get(5,6);
i.display();
test <float> f;
f.get(25.6,31.1);
f.display();
getch();
return 0;
}

Output:-

a:5
b:6
sum:11
a:25.6
b:31.1
sum:56.7
10)Write a program to implement the matrix ADT using the operations
supported by the ADT are:a)addition of two matrices

b)subtraction of two matrices

c)multiplication of two matrices

Program:-

#include<iostream>
#include<string.h>
#include<conio.h>

using namespace std;

struct matrixType{
int matDimension;
int matValues[10][10];
};

class MatrixADT{

private:
matrixType resultMatrix;

public:

//Member function declarations

void intializeResultMatrix(int);
matrixType add(matrixType, matrixType);
matrixType subtract(matrixType,matrixType);
matrixType multiply(matrixType,matrixType);
void printResult();
};

//Member functions of Matrix class to be defined here


matrixType MatrixADT::add(matrixType M1, matrixType M2)
{
int i,j;
for(i=0;i<M1.matDimension;i++)
for(j=0;j<M2.matDimension;j++)
{

resultMatrix.matValues[i][j]=M1.matValues[i][j]+M2.matValues[i][j];
}
return (M1);
}

matrixType MatrixADT::subtract(matrixType M1, matrixType M2)


{
int i,j;
for(i=0;i<M1.matDimension;i++)
for(j=0;j<M2.matDimension;j++)
{
resultMatrix.matValues[i][j]=M1.matValues[i][j]-
M2.matValues[i][j];
}

return (M1);
}

matrixType MatrixADT::multiply(matrixType M1, matrixType M2)


{
int i,j,k;
for(i=0;i<M1.matDimension;i++)
for(j=0;j<M2.matDimension;j++)
for(k=0;k<M1.matDimension;k++)
{

resultMatrix.matValues[i][j]+=M1.matValues[i][k]*M2.matValues[k][j];
}

return (M1);
}

void MatrixADT::intializeResultMatrix(int dim)


{
int i,j;
resultMatrix.matDimension=dim;
for(i=0;i<dim;i++)
for(j=0;j<dim;j++)
{
resultMatrix.matValues[i][j]=0;
}

int main(){

MatrixADT maX;
matrixType M1, M2;
char op;
int dim;
cin>>dim;
cin>>op;
M1.matDimension=M2.matDimension=dim;
int i,j;

for(i=0;i<dim;i++)
for(j=0;j<dim;j++)
cin>>M1.matValues[i][j];

for(i=0;i<dim;i++)
for(j=0;j<dim;j++)
cin>>M2.matValues[i][j];

maX.intializeResultMatrix(dim);
switch(op)
{
case '+' : M1=maX.add(M1,M2);
break;
case '-' : M1=maX.subtract(M1,M2);
break;
case '*' : M1=maX.multiply(M1,M2);

cout<<"hello";
break;
}

maX.printResult();
getch();
return (0);
}

void MatrixADT::printResult()
{
int i,j;
for (i=0;i<resultMatrix.matDimension;i++){
for (j=0; j<resultMatrix.matDimension-1;j++){
cout<<resultMatrix.matValues[i][j]<<" ";
}
cout <<resultMatrix.matValues[i][j]<<"\n";
}
cout <<"Done";
}

Output:-

3 +
1 2 3
4 5 6
7 8 9
9 8 7
6 5 4
3 2 1

10 10 10
10 10 10
10 10 10
Done

11) Write a program to accept two stacks input from the user and perform
the operations on it using stack class availate in STL

Program :-

#include<iostream>
#include<conio.h>
#include<stack>
using namespace std;
int main()
{
stack<int>s;
stack<int>s1;
s.push(3);
s.push(5);
s.push(7);
s1.push(6);
s1.push(2);
s1.push(9);
while(!s.empty()&&!s1.empty())
{

cout<<"operation on first stack:"<<endl;


cout<<"top()->"<<s.top()<<endl<<"size()->"<<s.size()<<endl;
cout<<"operation on second stack:"<<endl;
cout<<"top()->"<<s1.top()<<endl<<"size()->"<<s1.size()<<endl;
s.pop();
s1.pop();
}
}

Output:-

operation on first stack:


top()->7
size()->3
operation on second stack:
top()->9
size()->3
operation on first stack:
top()->5
size()->2
operation on second stack:
top()->2
size()->2
operation on first stack:
top()->3
size()->1
operation on second stack:
top()->6
size()->1

12)Write a program implementing a queue using STL

Program:-

#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue<string>animals;
animals.push("cat");
animals.push("dog");
cout<<"queue:";
while(!animals.empty())
{
cout<<animals.front()<<",";
cout<<animals.back()<<",";
cout<<animals.size()<<",";
animals.pop();
}
cout<<endl;
return 0;
}

Output:-

queue:cat,dog,2,dog,dog,1,

13)Write a program implementing a circular queue using STL

Program:-

// C or C++ program for insertion and


// deletion in Circular Queue
#include<bits/stdc++.h>
using namespace std;

class Queue
{
// Initialize front and rear
int rear, front;

// Circular Queue
int size;
int *arr;
public:
Queue(int s)
{
front = rear = -1;
size = s;
arr = new int[s];
}

void enQueue(int value);


int deQueue();
void displayQueue();
};

/* Function to create Circular queue */


void Queue::enQueue(int value)
{
if ((front == 0 && rear == size-1) ||
(rear == (front-1)%(size-1)))
{
printf("\nQueue is Full");
return;
}

else if (front == -1) /* Insert First Element */


{
front = rear = 0;
arr[rear] = value;
}

else if (rear == size-1 && front != 0)


{
rear = 0;
arr[rear] = value;
}

else
{
rear++;
arr[rear] = value;
}
}

// Function to delete element from Circular Queue


int Queue::deQueue()
{
if (front == -1)
{
printf("\nQueue is Empty");
return INT_MIN;
}

int data = arr[front];


arr[front] = -1;
if (front == rear)
{
front = -1;
rear = -1;
}
else if (front == size-1)
front = 0;
else
front++;

return data;
}

// Function displaying the elements


// of Circular Queue
void Queue::displayQueue()
{
if (front == -1)
{
printf("\nQueue is Empty");
return;
}
printf("\nElements in Circular Queue are: ");
if (rear >= front)
{
for (int i = front; i <= rear; i++)
printf("%d ",arr[i]);
}
else
{
for (int i = front; i < size; i++)
printf("%d ", arr[i]);

for (int i = 0; i <= rear; i++)


printf("%d ", arr[i]);
}
}

/* Driver of the program */


int main()
{
Queue q(5);

// Inserting elements in Circular Queue


q.enQueue(14);
q.enQueue(22);
q.enQueue(13);
q.enQueue(-6);

// Display elements present in Circular Queue


q.displayQueue();

// Deleting elements from Circular Queue


printf("\nDeleted value = %d", q.deQueue());
printf("\nDeleted value = %d", q.deQueue());

q.displayQueue();

q.enQueue(9);
q.enQueue(20);
q.enQueue(5);

q.displayQueue();

q.enQueue(20);
return 0;
}

Output:-

Elements in Circular Queue are: 14 22 13 -6


Deleted value = 14
Deleted value = 22
Elements in Circular Queue are: 13 -6
Elements in Circular Queue are: 13 -6 9 20 5
Queue is Full

14)Write a program to convert an infix expression to postfix expression


using stacks in STL

Program:-

//Using inbuilt stack library to create stack


#include <iostream>
#include <stack>
using namespace std;

int priority (char alpha){


if(alpha == '+' || alpha =='-')
return 1;

if(alpha == '*' || alpha =='/')


return 2;

if(alpha == '^')
return 3;

return 0;
}
string convert(string infix)
{
int i = 0;
string postfix = "";
// using inbuilt stack< > from C++ stack library
stack <int>s;

while(infix[i]!='\0')
{
// if operand add to the postfix expression
if(infix[i]>='a' && infix[i]<='z'|| infix[i]>='A'&&
infix[i]<='Z')
{
postfix += infix[i];
i++;
}
// if opening bracket then push the stack
else if(infix[i]=='(')
{
s.push(infix[i]);
i++;
}
// if closing bracket encounted then keep popping from stack
until
// closing a pair opening bracket is not encountered
else if(infix[i]==')')
{
while(s.top()!='('){
postfix += s.top();
s.pop();
}
s.pop();
i++;
}
else
{
while (!s.empty() && priority(infix[i]) <=
priority(s.top())){
postfix += s.top();
s.pop();
}
s.push(infix[i]);
i++;
}
}
while(!s.empty()){
postfix += s.top();
s.pop();
}

cout << "Postfix is : " << postfix; //it will print postfix
conversion
return postfix;
}

int main()
{
string infix = "((a+(b*c))-d)";
string postfix;
postfix = convert(infix);

return 0;
}

Output:-

Postfix is : abc*+d-

15)Write a program to perform all operations of single linked list using


forward list in stl

Program:-1)

// CPP program to illustrate


// Implementation of begin() function
#include <forward_list>
#include <iostream>
using namespace std;
int main()
{
// declaration of forward list container
forward_list<int> myflist{ 1, 2, 3, 4, 5 };

// using begin() to print list


for (auto it = myflist.begin(); it != myflist.end(); ++it)
cout << ' ' << *it;
return 0;
}

Output:-

1 2 3 4 5

2)

// CPP program to illustrate


// Implementation of end() function

#include& lt; forward_list & gt;


#include& lt; iostream & gt;
using namespace std;

int main()
{
// declaration of forward list container
forward_list& lt;
int& gt;
myflist{ 1, 2, 3, 4, 5 };

// using end() to print forward list


for (auto it = myflist.begin(); it != myflist.end();
++it)
cout& lt;
<
' ' & lt;
<
*it;
return 0;
}

Output:-

1 2 3 4 5

16)Write a program to implement binary search tree using traverse the


tree using any traversal schema

Program:-

// Binary Search Tree operations in C++

#include <iostream>
using namespace std;

struct node {
int key;
struct node *left, *right;
};

// Create a node
struct node *newNode(int item) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

// Inorder Traversal
void inorder(struct node *root) {
if (root != NULL) {
// Traverse left
inorder(root->left);

// Traverse root
cout << root->key << " -> ";

// Traverse right
inorder(root->right);
}
}

// Insert a node
struct node *insert(struct node *node, int key) {
// Return a new node if the tree is empty
if (node == NULL) return newNode(key);

// Traverse to the right place and insert the node


if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

return node;
}

// Find the inorder successor


struct node *minValueNode(struct node *node) {
struct node *current = node;

// Find the leftmost leaf


while (current && current->left != NULL)
current = current->left;

return current;
}
// Deleting a node
struct node *deleteNode(struct node *root, int key) {
// Return if the tree is empty
if (root == NULL) return root;

// Find the node to be deleted


if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else {
// If the node is with only one child or no child
if (root->left == NULL) {
struct node *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct node *temp = root->left;
free(root);
return temp;
}

// If the node has two children


struct node *temp = minValueNode(root->right);

// Place the inorder successor in position of the node to be deleted


root->key = temp->key;

// Delete the inorder successor


root->right = deleteNode(root->right, temp->key);
}
return root;
}

// Driver code
int main() {
struct node *root = NULL;
root = insert(root, 8);
root = insert(root, 3);
root = insert(root, 1);
root = insert(root, 6);
root = insert(root, 7);
root = insert(root, 10);
root = insert(root, 14);
root = insert(root, 4);

cout << "Inorder traversal: ";


inorder(root);

cout << "\nAfter deleting 10\n";


root = deleteNode(root, 10);
cout << "Inorder traversal: ";
inorder(root);
}
Output:-

Inorder traversal: 1 -> 3 -> 4 -> 6 -> 7 -> 8 -> 10 -> 14 ->
After deleting 10
Inorder traversal: 1 -> 3 -> 4 -> 6 -> 7 -> 8 -> 14 ->

You might also like