AVL tree(c++), program keeps on crashing - c++

I am working on an exercise in processing an AVL tree. The debugger shows no errors. I ran the program and it is supposed to output an output text file. However the program crashes every time.
#include <stdio.h>
#include <assert.h>
#include <algorithm>
#include <vector>
using namespace std;
struct node
{
int key;
int height;
node *left, *right;
node(int k)
{
key = k;
height = 1;
left = right = 0;
}
};
void pre_order(node* root)
{
if(root == 0) return;
printf("%d", root->key);
printf(" ");
pre_order(root->left);
pre_order(root->right);
}
void in_order(node* root)
{
in_order(root->left);
printf("%d", root->key);
printf(" ");
in_order(root->right);
}
int height(node* r)
{
return r ? r->height : 0;
}
void update_height(node* root)
{
if(root == 0) return;
int hl = height(root->left), hr = height(root->right);
root->height = std::max(hl, hr) + 1;
}
node* right_rotate(node* ref_root)
{
assert(ref_root && ref_root->left);
node *a = ref_root, *b = ref_root->left;
a->left = b->right;
b->right = a;
update_height(a);
update_height(b);
return b;
}
node* left_rotate(node* ref_root)
{
assert(ref_root && ref_root->right);
node *c = ref_root, *d = ref_root->right;
c->right = d->left;
d->left = c;
update_height(c);
update_height(d);
return d;
}
node* maintain(node* ref_root)
{
if(ref_root == 0) return ref_root;
update_height(ref_root);
node* ret = ref_root;
if(height(ref_root->left) > height(ref_root->right) + 1)
{
node* p = ref_root->left;
if( height(p->left) < height(p->right) )
ref_root->left = left_rotate(p);
ret = right_rotate(ref_root);
}
else if(height(ref_root->right) > height(ref_root->left) + 1)
{
node* p = ref_root->right;
if(height(p->right) < height(p->left)){
ref_root->right = right_rotate(p);
}
ret = left_rotate(ref_root);
}
return ret;
}
node* insert_key(int key, node* ref_root)
{
if(ref_root == 0)
{
return ref_root = new node(key);
}
if(key < ref_root->key){
node* child = insert_key(key, ref_root->left);
ref_root->left = child;
}
else if(key > ref_root->key){
node* child = insert_key(key, ref_root->right);
ref_root->right = child;
}
else
assert(0);
return maintain(ref_root);
}
vector<node*> minimum(node* T) {
vector<node*> x;
node* y = T;
while (y->left != NULL) {
x.push_back(y->left);
}
return x;
}
node* delete_key(int key, node* ref_root)
{
if(key < ref_root->key){
node* child = delete_key(key, ref_root->left);
ref_root->left = child;
}
else if(key > ref_root->key){
node* child = delete_key(key, ref_root->right);
ref_root->right = child;
}
else
{
if(ref_root->left && ref_root->right)
{
vector <node*> y = minimum(ref_root->right);
node* successor = y.back();
node* sParent = y[y.size()-2];
ref_root->key = successor->key;
sParent->left = successor->right;
}
else
{
if(ref_root->left != NULL){
ref_root = ref_root->left;
}
else if(ref_root->right != NULL){
ref_root = ref_root->right;
}
}
}
return maintain(ref_root);
}
int main()
{
node *root = 0;
char op[10] = "";
int k;
while(true)
{
scanf("%s", op);
if(op[0] == 'E') break;
switch(op[0])
{
case 'A': scanf("%d", &k); root = insert_key(k, root); break; //Insert
case 'D': scanf("%d", &k); root = delete_key(k, root); break;//Delete
case 'P': pre_order(root); printf("\n"); break;//preorder
case 'I': in_order(root); printf("\n"); break;//inorder
default: assert(0);
}
}
return 0;
}

There is no check in the in_order function that root is not NULL.

Related

Quicksort Algorithm in a doubly linked list

I want to sort a list by last names with the algorithm of Quicksort but when exchanging the elements it does not work, it leaves them as they were
In this part the values of the chains are exchanged
void swap(string* a, string* b){
cout<<"A and B are "<<*a<<" - "<<*b<<endl;
string t = *a;
*a = *b;
cout<<" A is ->"<<*a<<endl;
*b= t;
cout<<"B is ->"<<*b<<endl;
}
This is where the partition is made. I have noticed that when * i and * j take values they are exactly the same names and therefore can not be compared later. It seems strange to me that this list works if it is a number but when it is strings this error occurs.
User *i = lower;
But this did not work at the end because the program crashed, but if you change the value of the string
User* partition(User *lower, User *high){
cout<<"Lower -> "<<lower->lastname<<endl;
cout<<"High -> "<<high->lastname<<endl;
string pivot = high->lastname;
User *i = bajo->prev;
for (User *j = lower; j != high; j = j->next)
{
if (j->lastname.compare(pivot)< 0)
{
i = (i == NULL)? lower : i->next;
cout<<"Atention J e I valen ->"<<i->lastname<<" - "<<j->lastname<<endl;
swap(&(i->lastname), &(j->lastname));
}
}
i = (i == NULL)? lower : i->lastname; // Similar to i++
swap(&(i->lastname), &(alto->lastname));
return i;
}
What am I failing? How can I make it really take the desired value.
EDITED:
This is the source code
#include <iostream>
#include<iomanip>
#include <string>
#include<cstdlib>
using namespace std;
class User
{
public :
string lastname;
User *next;
User *prev;
User()
{
lastname= "";
next=NULL;
prev=NULL;
}
int empty(User *listt)
{
if(listt == NULL)
{
return 1;
}
else
{
return 0;
}
}
User *Insert(User *listt, string lastName)
{
User *temp = new User();
if(empty(listt))
{
temp->lastname=lastName;
listt = temp;
}
else
{
temp->lastname=lastName;
listt->prev=temp;
temp->next=listt;
listt=temp;
}
return listt;
}
void swap(string* a, string* b)
{
string t = *a;
*a = *b;
*b= t;
}
User* partition(User* lower, User* high)
{
cout<<"Lower -> "<<lower->lastname<<endl;
cout<<"High -> "<<high->lastname<<endl;
string pivot = high->lastname;
User *i = lower->prev;
for (User *j = lower; j != high; j = j->next)
{
if (j->lastname.compare(pivot)< 0)
{
i = (i == NULL)? lower : i->next;
swap(&(i->lastname), &(j->lastname));
}
}
i = (i == NULL)? lower : i->next; // Similar to i++
swap(&(i->lastname), &(high->lastname));
return i;
}
User *Last(User *listt)
{
User *temp = listt;
while(temp && temp ->next)
temp=temp->next;
return temp;
}
void _quickSort( User* lower, User* high)
{
if(high != NULL && lower != high&&lower!= high->next)
{
User *p = partition(lower,high);
_quickSort(lower,p->next); //I change this part
_quickSort(p->next,high);
}
}
void quickSort(User *listt)
{
User *h = Last(listt);
_quickSort(listt, h);
}
User *Display(User *listt)
{
if(empty(listt))
{
cout<<"List empty"<<endl;
}
else
{
User *temp = new User();
temp = listt;
while(temp!= NULL)
{
cout<<"The last name is -> "<<temp->lastname<<endl;
temp=temp->next;
}
}
return listt;
}
};
int main()
{
User *listt = NULL;
User y;
bool exit = false;
int opc;
string lastName;
while(!exit)
{
cout<<"1.-Insert an element"<<endl;
cout<<"2.-Sort element-(Quicksort)"<<endl;
cout<<"3.-Show elements"<<endl;
cout<<"4.-Exitt"<<endl;
cin>>opc;
switch(opc)
{
case 1:
cout<<"Inser your last name"<<endl;
cin>>lastName;
listt=y.Insert(listt,lastName);
system("pause");
system("cls");
break;
case 2:
cout<<"Sorting...."<<endl;
y.quickSort(listt);
system("pause");
system("cls");
break;
case 3:
cout<<"Display..."<<endl;
y.Display(listt);
system("pause");
system("cls");
break;
case 4:
exit = true;
break;
}
}
}
Actually your swap function seems working but string t = *a; usage is kind of weird because *a is considered as an int value so you should not assign it to a string although the compiler can handle it either way. On the other hand I guess what you mentioned is to copy the value of "a" into a temporary string and it should be done as string* t = a; and then you can do b = t; but instead of that passing by reference is a better practice such as
void swap(string &a, string &b){
string t = a;
a = b;
b= t;
}
and you may want to check your Quick-sort implementation, see the reference on this page
_quickSort(lower,p->next); //I change this part
This should be p->prev. The correct function:
void _quickSort(User* lower, User* high)
{
if(high != NULL && lower != high&&lower != high->next)
{
User *p = partition(lower, high);
_quickSort(lower, p->prev); //change it back!
_quickSort(p->next, high);
}
}
Additionally there is resource leak in Display. Don't allocate new items in display function:
User *Display(User *listt)
{
if(empty(listt))
{
cout<<"List empty"<<endl;
}
else
{
//User *temp = new User(); <== don't allocate new item here
User *temp = listt;
while(temp!= NULL)
{
cout<<"The last name is -> "<<temp->lastname<<endl;
temp=temp->next;
}
}
return listt;
}
Testing with a 1000 items:
class User
{
public:
class Node
{
public:
string lastname;
Node *next;
Node *prev;
Node()
{
prev = next = nullptr;
}
};
Node *head;
User()
{
head = nullptr;
}
void Insert(string val)
{
Node *temp = new Node;
temp->lastname = val;
if (head)
{
head->prev = temp;
temp->next = head;
}
head = temp;
}
void swap(string &a, string &b)
{
string t = a;
a = b;
b = t;
}
Node *Tail()
{
Node *temp = head;
while(temp && temp->next)
temp = temp->next;
return temp;
}
Node* partition(Node* left, Node* right)
{
string pivot = right->lastname;
Node *i = left->prev;
for(Node *j = left; j != right; j = j->next)
{
if(j->lastname < pivot)
{
i = (i == nullptr) ? left : i->next;
swap(i->lastname, j->lastname);
}
}
i = (i == nullptr) ? left : i->next; // Similar to i++
swap(i->lastname, right->lastname);
return i;
}
void quickSort(Node* left, Node* right)
{
if(!left || !right || left == right || left == right->next)
return;
Node *p = partition(left, right);
quickSort(left, p->prev);
quickSort(p->next, right);
}
void quickSort()
{
quickSort(head, Tail());
}
void Display()
{
string last;
for (Node *n = head; n; n = n->next)
{
if(n->lastname < last)
{
cout << "error ***\n";
break;
}
last = n->lastname;
cout << n->lastname << endl;
}
}
};
int main()
{
User list;
list.Insert("z");
list.Insert("c");
list.Insert("a");
list.Insert("g");
for(int i = 0; i < 1000; i++)
{
string str;
for (int j = 0; j < 3; j++)
str.push_back('a' + rand() % 26);
list.Insert(str);
}
list.quickSort();
list.Display();
return 0;
}

problems in implementation of avl

I am trying to insert 0 through 11 into avl and then delete 4, 5, 6 in that order. I am getting sigserv error while deleting 6 in rr_rotation function. This is the first time I am implementing avl and I am new to programming. Where am I going wrong? I added a few comments for my own understanding and to track where the error has occurred. Here is my code:
#include<bits/stdc++.h>
using namespace std;
#define pow2(n) (1 << (n))
struct avl_node {
int data;
//int size;
struct avl_node *left;
struct avl_node *right;
}*root;
class avlTree {
public:
int height(avl_node *);
int diff(avl_node *);
avl_node *rr_rotation(avl_node *);
avl_node *ll_rotation(avl_node *);
avl_node *lr_rotation(avl_node *);
avl_node *rl_rotation(avl_node *);
avl_node* balance(avl_node *);
avl_node* insert(avl_node *, int);
int getBalance(avl_node*);
int getSize(avl_node*);
avl_node* minValueNode(avl_node*);
avl_node* del(avl_node *, int);
void inorder(avl_node *);
void preorder(avl_node *);
int kthsmallest(avl_node*, int);
avlTree() {
root = NULL;
}
};
int avlTree::height(avl_node *temp) {
int h = 0;
if (temp != NULL) {
int l_height = height(temp->left);
int r_height = height(temp->right);
int max_height = max(l_height, r_height);
h = max_height + 1;
}
return h;
}
int avlTree::diff(avl_node *temp) {
int l_height = height(temp->left);
int r_height = height(temp->right);
int b_factor = l_height - r_height;
return b_factor;
}
avl_node *avlTree::rr_rotation(avl_node *parent) {
avl_node *temp;
cout<<"inside rr rotation"<<endl;
cout<<"parent = "<<parent->data<<endl;
temp = parent->right;
if(temp == NULL)
cout<<"yes null 2"<<endl;
//cout<<"parent->right "<<temp->data<<endl;
parent->right = temp->left;
temp->left = parent;
cout<<"temp->left->data "<<temp->left->data<<endl;
return temp;
}
avl_node *avlTree::ll_rotation(avl_node *parent) {
avl_node *temp;
//cout<<"inside ll rotation"<<endl;
//cout<<"parent = "<<parent->data<<endl;
temp = parent->left;
parent->left = temp->right;
temp->right = parent;
return temp;
}
avl_node *avlTree::lr_rotation(avl_node *parent) {
avl_node *temp;
cout<<"inside lr rotation"<<endl;
cout<<"parent = "<<parent->data<<endl;
temp = parent->left;
parent->left = rr_rotation(temp);
return ll_rotation(parent);
}
avl_node *avlTree::rl_rotation(avl_node *parent) {
avl_node *temp;
cout<<"inside rl rotation"<<endl;
cout<<"parent = "<<parent->data<<endl;
temp = parent->right;
parent->right = ll_rotation(temp);
return rr_rotation(parent);
}
avl_node *avlTree::balance(avl_node *temp) {
int bal_factor = diff(temp);
if (bal_factor > 1) {
if (diff(temp->left) > 0)
temp = ll_rotation(temp);
else
temp = lr_rotation(temp);
} else if (bal_factor < -1) {
if (diff(temp->right) > 0)
temp = rl_rotation(temp);
else
temp = rr_rotation(temp);
}
return temp;
}
avl_node *avlTree::insert(avl_node *root, int value) {
//cout<<"Inside insert for val = "<<value<<endl;
if (root == NULL) {
root = new avl_node;
root->data = value;
root->left = NULL;
root->right = NULL;
return root;
} else if (value < root->data) {
root->left = insert(root->left, value);
root = balance(root);
} else if (value >= root->data) {
root->right = insert(root->right, value);
root = balance(root);
}
return root;
}
avl_node* avlTree::minValueNode(avl_node* node) {
avl_node* current = node;
while (current->left != NULL)
current = current->left;
return current;
}
int avlTree::getBalance(avl_node* N) {
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
avl_node* avlTree::del(avl_node *root, int value) {
cout<<"del for val = "<<value<<endl;
if (root == NULL){
cout<<"root is null here\n";
return root;
}
// If the key to be deleted is smaller than the
// root's key, then it lies in left subtree
if (value < root->data)
root->left = del(root->left, value);
// If the key to be deleted is greater than the
// root's key, then it lies in right subtree
else if (value > root->data)
root->right = del(root->right, value);
// if key is same as root's key, then This is
// the node to be deleted
else {
// node with only one child or no child
if ((root->left == NULL) || (root->right == NULL)) {
avl_node* temp = root->left ? root->left : root->right;
// No child case
if (temp == NULL) {
temp = root;
root = NULL;
cout<<"Root set to null\n";
}
else{
// One child case
cout<<temp->data<<" copied to root "<<root->data<<"\n";
*root = *temp;
// Copy the contents of
// the non-empty child
}
free(temp);
} else {
// node with two children: Get the inorder
// successor (smallest in the right subtree)
avl_node* temp = minValueNode(root->right);
// Copy the inorder successor's data to this node
root->data = temp->data;
// Delete the inorder successor
root->right = del(root->right, temp->data);
}
} // If the tree had only one node then return
if (root == NULL)
return root;
// STEP 2: UPDATE HEIGHT OF THE CURRENT NODE
//root->height = 1 + max(height(root->left),height(root->right));
// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to
// check whether this node became unbalanced)
int balance = getBalance(root);
cout<<"balance = "<<balance<<" for root "<<root->data<<endl;
if(root->right == NULL)
cout<<"yes null"<<endl;
// If this node becomes unbalanced, then there are 4 cases// Left Left Case
if (balance > 1 && getBalance(root->left) >= 0){
cout<<"balance1 = "<<getBalance(root->left)<<" for root "<<root->left->data<<endl;
avl_node* t = rr_rotation(root);
//root = rr_rotation(root);
cout<<"Root of the modified sub-tree is "<<t->data<<endl;
return t;
//rr_rotation(root);
}
// Left Right Case
if (balance > 1 && getBalance(root->left) < 0) {
cout<<"balance2 = "<<getBalance(root->left)<<" for root "<<root->left->data<<endl;
cout<<"prev root "<<root->left->data<<endl;
//root->left = ll_rotation(root->left);
root = lr_rotation(root);
cout<<"new root "<<root->data<<endl;
//return rr_rotation(root);
return root;
} // Right Right Case
if (balance < -1 && getBalance(root->right) <= 0){
cout<<"balance3 = "<<getBalance(root->right)<<" for root "<<root->right->data<<endl;
avl_node* t = rr_rotation(root);
cout<<"Root of the modified sub-tree is "<<t->data<<endl;
return t;
//return ll_rotation(root);
}
// Right Left Case
if (balance < -1 && getBalance(root->right) > 0) {
cout<<"balance4 = "<<getBalance(root->right)<<" for root "<<root->right->data<<endl;
//root->right = rr_rotation(root->right);
//return ll_rotation(root);
return rl_rotation(root);
}
return root;
}
void avlTree::inorder(avl_node *tree) {
if (tree == NULL)
return;
inorder(tree->left);
cout << tree->data << " ";
inorder(tree->right);
}
void avlTree::preorder(avl_node *tree) {
if (tree == NULL)
return;
cout << tree->data << " ";
preorder(tree->left);
preorder(tree->right);
}
int avlTree::getSize(avl_node* N){
if(N == NULL)
return 0;
return (getSize(N->left) + 1 + getSize(N->right));
}
int avlTree::kthsmallest(avl_node* N, int k){
int r = getSize(N->left) + 1;
if(k == r)
return N->data;
if(k < r)
return kthsmallest(N->left,k);
if(k > r)
return kthsmallest(N->right,k-r);
return -1;
}
int main(void) {
int n, i, x;
char s;
avlTree tree; for(i=0;i<12;i++){
root = tree.insert(root,i);
tree.preorder(root);
cout<<endl;
}
for(i=4;i<=6;i++){
root = tree.del(root,6);
tree.preorder(root);
cout<<endl;
}
return 0;
}

A count function that counts the leaf nodes of a height balanced tree

I'm writing a function that counts the leaf nodes of a height balanced tree using struct and pointers. The function takes 3 arguments: the tree, pointer to an array and the maximum depth of the tree. The length of the array is the maximum depth. When function is called the array is initialized to zero. The function recursively follows the tree structure,
keeping track of the depth, and increments the right counter whenever it reaches a leaf. The function does not follow any pointer deeper than maxdepth. The function returns 0 if there was no leaf at depth greater than maxdepth, and 1 if there was some pointer togreater depth. What is wrong with my code. Thanks.
typedef int object;
typedef int key;
typedef struct tree_struct { key key;
struct tree_struct *left;
struct tree_struct *right;
int height;
} tree_n;
int count_d (tree_n *tr, int *count, int mdepth)
{
tree_n *tmp;
int i;
if (*(count + 0) == NULL){
for (i =0; i<mdepth; i++){
*(count + i) = 0;
}
}
while (medepth != 0)
{
if (tr == NULL) return;
else if ( tree-> left == NULL || tree->right == NULL){
return (0);
}
else {
tmp = tr;
*(count + 0) = 1;
int c = 1;
while(tmp->left != NULL && tmp->right != NULL){
if(tmp-> left){
*(count + c) = 2*c;
tmp = tmp->left;
return count_d(tmp, count , mdepth);
}
else if(tmp->right){
*(count + c + 1) = 2*c + 1;
tmp = tmp->right;
return count_d(tmp,count, mdepth);
}
c++;
mpth--;
}
}
}
What is wrong with my code
One thing I noticed is that you are missing return in the recursive calls.
return count_d(tmp, count , mdepth);
// ^^^ Missing
There are two such calls. Make sure to add return to both of them.
Disclaimer: Fixing this may not fix all your problems.
Correct Function To Insert,Count All Nodes and Count Leaf Nodes
#pragma once
typedef int itemtype;
#include<iostream>
typedef int itemtype;
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
class Node
{
public:
Node* left;
Node* right;
itemtype data;
};
class BT
{
private:
int count = 0;
Node* root;
void insert(itemtype d, Node* temp);//Override Function
public:
BT();//Constructor
bool isEmpty();
Node* newNode(itemtype d);
Node* getroot();
void insert(itemtype d);//Function to call in main
int countLeafNodes(Node * temp);
int countAllNodes();//to count all nodes
}
BT::BT()//constructor
{
root = NULL;
}
bool BT::isEmpty()
{
if (root == NULL)
return true;
else
return false;
}
Node* BT::newNode(itemtype d)
{
Node* n = new Node;
n->left = NULL;
n->data = d;
n->right = NULL;
return n;
}
void BT::insert(itemtype d)//Function to call in main
{
if (isEmpty())
{
Node* temp = newNode(d);
root = temp;
}
else
{
Node* temp = root;
insert(d, temp);
}
count++;//to count number of inserted nodes
}
void BT::insert(itemtype d, Node* temp)//Private Function which is overrided
{
if (d <= temp->data)
{
if (temp->left == NULL)
{
Node* n = newNode(d);
temp->left = n;
}
else
{
temp = temp->left;
insert(d, temp);
}
}
else
{
if (temp->right == NULL)
{
temp->right = newNode(d);
}
else
{
temp = temp->right;
insert(d, temp);
}
}
}
int BT::countAllNodes()
{ return count; }
int BT::countLeafNodes(Node* temp)
{
int leaf = 0;
if (temp == NULL)
return leaf;
if (temp->left == NULL && temp->right == NULL)
return ++leaf;
else
{
leaf = countLeafNodes(temp->left) + countLeafNodes(temp->right);
return leaf;
}
}
void main()
{
BT t;
t.insert(7);
t.insert(2);
t.insert(3);
t.insert(15);
t.insert(11);
t.insert(17);
t.insert(18);
cout<<"Total Number Of Nodes:" <<t.countAllNodes() <<endl;
cout << "Leaf Nodes:" << t.countLeafNodes(t.getroot()) << endl;
_getch();
}
Output:
Ouput

Adjacency list to create graph and Breadth First Search (BFS) and Fepth First Search (DFS)

Here is my code which implements graph using adjacency list and do a Breadth First Search (BFS) and Depth First Search (DFS).
While creating graph and adding edges I am facing problem of a fault in creating graph. I am not sure of the pointer that I have used.
Can you suggest where am I wrong?
#include "Graph.h"
#include <iostream>
using namespace std;
int Graph::pop()
{
if (top = -1) {
cout << "empty";
return 0;
} else
return stack[top--];
}
void Graph::push(int value)
{
if (top >= 50) {
cout << "full";
} else
stack[++top] = value;
}
void Graph::add(int val)
{
if (rear != 49)
qu[++rear] = val;
else
cout << "full";
}
int Graph::del()
{
if (rear == front) {
cout << "empty";
return 0;
} else
front += 1;
return qu[front];
}
int Graph::gethead()
{
return rear;
}
int Graph::gettail()
{
return front;
}
node *Graph::createnode(int t)
{
node *temp;
temp = new node;
temp->val = t;
temp->next = NULL;
return temp;
}
Graph::Graph()
{
rear = -1;
front = -1;
top = -1;
}
Graph::Graph(int t)
{
struct arr r[t];
a = r;
for (int i = 0; i < t; i++) {
a[i].key = i;
a[i].begin = NULL;
a[i].end = NULL;
}
int q[t];
p = q;
for (int k = 0; k < t; k++) {
p[k] = 0;
}
}
void Graph::visited(int v1)
{
p[v1] = 1;
}
bool Graph::isvisited(int v1)
{
if (p[v1] == 1)
return true;
else
false;
}
void Graph::addEdge(int v1, int v2)
{
if (a[v1].begin == NULL) {
node *temp = createnode(v2);
a[v1].begin = temp;
a[v1].end = temp;
} else {
node *temp = createnode(v2);
node *temp1 = a[v1].end;
temp1->next = temp;
a[v1].end = temp;
}
if (a[v2].begin == NULL) {
node *temp = createnode(v1);
a[v2].begin = temp;
a[v2].end = temp;
} else {
node *temp = createnode(v1);
//node *temp2=a[v2].end;
//temp2->next=temp;
a[v2].end->next = temp;
//a[v2].end->next=temp;
a[v2].end = temp;
}
}
void Graph::deleteEdge(int v1, int v2)
{
node *temp;
temp = a[v1].begin;
if (a[v1].begin->val == v2) {
a[v1].begin = a[v1].begin->next;
delete(temp);
temp = NULL;
} else {
node *t = temp->next;
while (t != NULL) {
if (t->val == v2) {
temp->next = t->next;
delete(t);
} else {
temp = t;
t = t->next;
}
}
}
node *temp1;
temp1 = a[v2].begin;
if (a[v2].begin->val == v1) {
a[v2].begin = a[v2].begin->next;
delete(temp);
temp = NULL;
} else {
node *t = temp->next;
while (t != NULL) {
if (t->val == v1) {
temp->next = t->next;
delete(t);
} else {
temp = t;
t = t->next;
}
}
}
}
void Graph::BFS(int source)
{
add(source);
visited(source);
node *temp = a[source].begin;
while (temp != a[source].end) {
add(temp->val);
}
int r = del();
cout << r << endl;
while (gethead() != gettail()) {
int v1 = del();
visited(v1);
node *temp1;
temp1 = a[v1].begin;
while (temp1 != NULL) {
if (p[temp1->val] != 1) {
add(temp1->val);
temp1 = temp1->next;
} else
temp1 = temp1->next;
}
if (temp1 == NULL)
cout << v1 << endl;
}
}
void Graph::DFS(int source)
{
int c = source;
cout << c;
visited(c);
node *temp2 = a[source].begin;
while (a[source].end != NULL) {
push(temp2->val);
temp2 = temp2->next;
}
c = pop();
while (top != -1) {
node *temp = a[c].begin;
if (p[c] != 1) {
cout << c;
while (temp != NULL) {
push(temp->val);
temp = temp->next;
visited(c);
c = pop();
}
}
if (p[c] = 1) {
c = pop();
}
}
}
The first obvious mistake is that in line if (top = -1), the = should be replaced with ==.

C++ AVL Tree Deletion

So, I want to take input from a text file, then do some operations in an AVL tree. I could implement insertion, yet I can't build a solution for deletion in my mind. Can you help me? Here is the code.
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#include <fstream>
#include <stdlib.h>
#include <array>
#include <ctime>
using namespace std;
struct node
{
int data;
int height;
struct node *leftchild;
struct node *rightchild;
}*root;
class avlTree
{
public:
int height(node *);
int difference(node *);
node *rrtraversal(node *);
node *lltraversal(node *);
node *lrtraversal(node *);
node *rltraversal(node *);
node* balance(node *);
node* insert(node *, int );
void display(node *, int);
node *del(node *, int);
avlTree()
{
root = NULL;
}
};
int avlTree::height(node *temp)
{
int h = 0;
if (temp != NULL)
{
int l_height = height (temp->leftchild);
int r_height = height (temp->rightchild);
int max_height = max (l_height, r_height);
h = max_height + 1;
}
return h;
}
int avlTree::difference(node *temp)
{
int l_height = height (temp->leftchild);
int r_height = height (temp->rightchild);
int b_factor= l_height - r_height;
return b_factor;
}
node *avlTree::rrtraversal(node *parent)
{
node *temp;
temp = parent->rightchild;
parent->rightchild = temp->leftchild;
temp->leftchild = parent;
return temp;
}
node *avlTree::lltraversal(node *parent)
{
node *temp;
temp = parent->leftchild;
parent->leftchild = temp->rightchild;
temp->rightchild = parent;
return temp;
}
node *avlTree::lrtraversal(node *parent)
{
node *temp;
temp = parent->leftchild;
parent->leftchild = rrtraversal (temp);
return lltraversal (parent);
}
node *avlTree::rltraversal(node *parent)
{
node *temp;
temp = parent->rightchild;
parent->rightchild = lltraversal (temp);
return rrtraversal (parent);
}
node *avlTree::balance(node *temp)
{
int bal_factor = difference (temp);
if (bal_factor > 1)
{
if (difference (temp->leftchild) > 0)
temp = lltraversal (temp);
else
temp = lrtraversal (temp);
}
else if (bal_factor < -1)
{
if (difference (temp->rightchild) > 0)
temp = rltraversal (temp);
else
temp = rrtraversal (temp);
}
return temp;
}
node *avlTree::insert(node *root, int value)
{
if (root == NULL)
{
root = new node;
root->data = value;
root->leftchild = NULL;
root->rightchild = NULL;
return root;
}
else if (value < root->data)
{
root->leftchild = insert(root->leftchild, value);
root = balance (root);
}
else if (value >= root->data)
{
root->rightchild = insert(root->rightchild, value);
root = balance (root);
}
return root;
}
void avlTree::display(node *ptr, int level)
{
int i;
if (ptr!=NULL)
{
display(ptr->rightchild, level + 1);
printf("\n");
for (i = 0; i < level && ptr != root; i++)
cout<<" ";
cout<<ptr->data;
display(ptr->leftchild, level + 1);
}
}
node *avlTree::del(node *root, int x)
{
node *d;
if ( x < root->data){
del(root->leftchild,x);
}
else if (x > root->data){
del(root->rightchild,x);
}
else if ((root->leftchild == NULL) && (root->rightchild == NULL))
{
d=root;
free(d);
root=NULL;
}
else if (root->leftchild == NULL)
{
d=root;
free(d);
root= root->rightchild;
}
else if (root->rightchild == NULL)
{
d=root;
root=root->leftchild;
free(d);
}
return root;
}
int main()
{
ifstream myFile("file.txt");
int a = 0;
std::array<string,512> arrayTest;
int index = 0;
string content;
avlTree avl;
while (myFile >> content){
arrayTest[index] = content;
index++;
}
clock_t startTime = clock();
for(a = 0; a < arrayTest.size();a++){
if(arrayTest[a] == "i"){
root = avl.insert(root, std::stoi(arrayTest[a+1]));
}
}
avl.display(root,1);
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
cout << "\n\n" << timeInSeconds << " secs\n";
}
In file, the content is like this. i 1 i 2 i 3 i 4 i 5 d 3
If program sees i, it will do an insert operation. Likewise, if it sees d, it will do a delete operation.
Did you try free() function?
free(node);