Syed Mohamid Raza Bcs221098
Syed Mohamid Raza Bcs221098
class node
{
public:
int data;
node* left;
node* right;
node(int x)
{
data = x;
left = NULL;
right = NULL;
}
};
class BST
{
public:
node* root;
BST()
{
root = NULL;
}
if (r->data > x)
{
{
return;
}
in_order(r->left);
void pre_order(node* r)
{
if (r == NULL)
{
return;
}
void post_order(node* r)
{
if (r == NULL)
{
return;
}
pre_order(r->left);
pre_order(r->right);
cout << r->data << " ";
}
{
if (r == NULL)
{
cout << "Not Found" << endl;
return;
}
else if (val == r->data)
{
cout << r->data << " Value Found" << endl;
}
else if (val < r->data)
{
search(r->left, val);
}
else
{
search(r->right, val);
}
}
int count_nodes(node* r)
{
static int count = 0;
if (r == NULL)
{
return 0;
}
else
{
count++;
count_nodes(r->left);
count_nodes(r->right);
}
return count;
}
{
node* successor = NULL;
while (r != NULL)
{
r = r->left;
}
}
int x;
if (successor == NULL)
{
x = 0;
}
else
{
x = successor->data;
}
while (r != NULL)
{
if (r->data >= val)
{
r = r->left;
}
else
{
predecessor = r;
r = r->right;
}
}
int x;
if (predecessor == NULL)
{
x = 0;
}
else
{
x = predecessor->data;
}
{
r->left = deleterec(r->left, val);
}
else if (val > r->data)
{
r->right = deleterec(r->right, val);
}
else
{
if (r->left == NULL)
{
node* temp = r->right;
delete r;
return temp;
}
else if (r->right == NULL)
{
node* temp = r->left;
delete r;
return temp;
}
private:
node* findMinValueNode(node* r)
{
node* current = r;
return current;
}
};
int main()
{
BST b1;
b1.insert(2);
b1.insert(7);
b1.insert(3);
b1.insert(1);
b1.insert(15);
b1.pre_order(b1.root);
cout << endl;
b1.search(b1.root, 10);
b1.search(b1.root, 2);
b1.successor(1, b1.root);
b1.predecessor(7, b1.root);
b1.deleteNode(3);
cout << "Inorder after deleting 3: ";
b1.in_order(b1.root);
cout << endl;
return 0;
}
Output:
Question :2
#include <iostream>
using namespace std;
class node
{
public:
int data;
node* left;
node* right;
node(int x)
{
data = x;
left = NULL;
right = NULL;
}
private:
};
class BST
{
public:
node* root;
BST()
{
root = NULL;
}
node* insertrec(int x,node *r)
{
if (r==NULL)
{
node* newNode = new node(x);
return newNode;
}
if (r->data > x)
{
r->left = insertrec(x, r->left);
}
else if (r->data < x)
{
r->right = insertrec(x, r->right);
}
return r;
}
void insert(int val)
{
root=insertrec(val, root);
}
node* findLowestCommonAncestor(node* root, int x, int y) {
while (root != NULL) {
if (root->data > x && root->data > y) {
root = root->left;
}
else if (root->data < x && root->data < y) {
root = root->right;
}
else {
return root;
}
}
return NULL;
}
private:
};
int main()
{
BST b1;
b1.insert(2);
b1.insert(15);
b1.insert(10);
b1.insert(25);
b1.insert(15);
b1.insert(30);
b1.insert(20);
b1.insert(8);
b1.insert(12);
b1.insert(22);
b1.insert(18);
b1.insert(9);
b1.insert(6);