What factors could cause bad_alloc? - c++

I was writing an AVL tree implementation but got an error due to bad_alloc on another platform. However, the code works perfectly for me in CS50 IDE without any warning.
In my code, I used new keyword to declare objects and I did deleted them after using.
My question is that what other factors could result in this bad_alloc error? And how can I solve it?
#include <vector>
using namespace std;
class node {
public:
int value;
int height;
node* left;
node* right;
node();
};
// freeing the dynamically allocated memory
void freeTree(node* root){
if((root->left) != nullptr){
freeTree(root->left);
}
if((root->right) != nullptr){
freeTree(root->right);
}
delete root;
}
node::node(){
height = 1;
}
int get_height(node* n){
if(n == NULL){
return 0;
}
return n->height;
}
int get_balance_factor(node* n){
if(n == NULL){
return 0;
}
if(n->value == 0){
return 0;
}
return (get_height(n->left))-(get_height(n->right));
}
// prints out the AVL tree by inorder traversal
void inorder(node* root){
if((root->left) != nullptr){
inorder(root->left);
}
cout << root->value << ' ';
if((root->right) != nullptr){
inorder(root->right);
}
}
// prints out the AVL tree by preorder traversal
void preorder(node* root){
cout << root->value << ' ';
if((root->left) != nullptr){
preorder(root->left);
}
if((root->right) != nullptr){
preorder(root->right);
}
}
// prints out the AVL tree by postorder traversal
void postorder(node* root){
if((root->left) != nullptr){
postorder(root->left);
}
if((root->right) != nullptr){
postorder(root->right);
}
cout << root->value << ' ';
}
node* left_rotation(node* root){
node* temp = root->right;
root->right = root->right->left;
temp->left = root;
root->height = max(get_height(root->left),get_height(root->right))+1;
temp->height = max(get_height(temp->left),get_height(temp->right))+1;
return temp;
}
node* right_rotation(node* root){
node* temp = root->left;
root->left = root->left->right;
temp->right = root;
root->height = max(get_height(root->left),get_height(root->right))+1;
temp->height = max(get_height(temp->left),get_height(temp->right))+1;
return temp;
}
node* add_node(int k, node* root){
// cout << "inserting " << k << endl;
// BST insertion
if(root == NULL){
node* temp = new node();
temp->value = k;
return temp;
}
if(root->value == 0){
node* temp = new node();
temp->value = k;
return temp;
}
else if(k > (root->value)){
root->right = add_node(k, root->right);
}
else if(k < (root->value)){
root->left = add_node(k, root->left);
}
else{
return root;
}
root->height = max(get_height(root->left),get_height(root->right))+1;
// rebalancing
int bf = get_balance_factor(root);
// right-heavy tree
if(bf < -1){
return left_rotation(root);
}
// left-heave tree
if(bf > 1){
return right_rotation(root);
}
return root;
}
int main(){
// initializing an avl tree
node* root = new node();
// handling input
vector<string> input;
while(true){
string temp;
cin >> temp;
input.push_back(temp);
if(cin.peek() == 32){
cin.ignore();
}
else if(cin.peek() == 10){
break;
}
}
// processing input
for(int i = 0; i < (int)input.size()-1; i++){
string temp = input[i];
char operation = temp[0];
int number = stoi(temp.substr(1, temp.length()-1));
if(operation == 'A'){
root = add_node(number, root);
}
else if(operation == 'D'){
// call delete node function
}
}
// traversal
string traversal = input[input.size()-1];
if(traversal == "PRE"){
preorder(root);
}
else if(traversal == "IN"){
inorder(root);
}
else if(traversal == "POST"){
postorder(root);
}
freeTree(root);
return 0;
}```

Related

Binary search tree algorithm crashing when passing a parameter that isn't in the tree to the search function

i tried building a binary search tree, everything worked fine when i gave it parameters that were in in the tree, but i wanted to see if it would print 0 when it couldn't find the int in the tree instead when i call search it's crashing.
i tried adding a condition after the first if statement but that ruined the recursion
here's the code:
struct node
{
int data;
node* left;
node* right;
node(int d)
{
data = d;
left = right = NULL;
}
};
node* insert(node *root, int n)
{
if(root == NULL)
{
return new node(n);
}
else
{
node* y;
if(n <= root->data)
{
y = insert(root->left, n);
root->left = y;
}
else
{
y = insert(root->right, n);
root->right = y;
}
return root;
}
}
node* search(node *root,int n)
{
if(root == NULL || root->data == n)
{
return root;
}
if(root->data < n)
{
return search(root->right, n);
}
return search(root->left, n);
}
int treemax(node *root)
{
while(root->right != NULL)
{
root = root->right;
}
return root->data;
}
int treemin(node *root)
{
while(root->left != NULL)
{
root = root->left;
}
return root->data;
}
int main()
{
node *R = NULL;
R = insert(R, 33);
insert(R,12);
insert(R, 40);
insert(R, 36);
insert(R, 21);
cout << search(R, 65)->data << endl;
}
Your problem is that you are trying to access null pointer. Pointer returned from search(R,65) is null because аt last step your root->right is null.
If you want to return 0 if no elements is found you can replace your last line with this:
node *result = search(R, 65);
if (result)
cout << result->data << endl;
else
cout << "0" << endl;
Below is a working example. I have added some comments that show what things you can change in the above program to make it safe or better.
#include<iostream>
struct node
{
//always initialize built-in type data members
int data = 0;//initialize any built in type otherwise it will have garbage value
node* left = nullptr;//initialize any built type as stated above
node* right = nullptr;//initialize any built in type as stated above
node(int d)
{
data = d;
left = right = nullptr;
}
};
node* insert(node *root, int n)
{
if(root == nullptr)
{
return new node(n);
}
else
{
node* y;
if(n <= root->data)
{
y = insert(root->left, n);
root->left = y;
}
else
{
y = insert(root->right, n);
root->right = y;
}
return root;
}
}
node* search(node *root,int n)
{
if(root == nullptr || root->data == n)
{
return root;
}
if(root->data < n)
{
return search(root->right, n);
}
return search(root->left, n);
}
int treemax(node *root)
{
while(root->right != nullptr)
{
root = root->right;
}
return root->data;
}
int treemin(node *root)
{
while(root->left != nullptr)
{
root = root->left;
}
return root->data;
}
int main()
{
node *R = nullptr;
R = insert(R, 33);
insert(R,12);
insert(R, 40);
insert(R, 36);
insert(R, 21);
//std::cout << search(R, 65)->data << std::endl;
node *value = search(R, 65);
//check if the pointer is valid
if(value)
{
std::cout<< value->data <<std::endl;
}
else
{
std::cout<<"cannot access nullptr"<<std::endl;
}
}
The error was because search(R, 65); was returning NULL and you were trying to access a NULL pointer's data member value.
When you run
cout << search(R, 65)->data << endl;
search(R, 65) returns NULL. You can't dereference NULL by doing ->data on it. You probably want:
Node* result = search(R, 65);
if (result)
{
cout << result->data << endl;
}
else
{
cout << "Not found" << endl;
}

error in remove method for singly linked list

#include <iostream>
using namespace std;
template <typename Object>
struct Node
{
Object data;
Node* next;
Node(const Object &d = Object(), Node *n = (Object)NULL) : data(d), next(n) {}
};
template <typename Object>
class singleList
{
public:
singleList() { init(); }
~singleList() { eraseList(head); }
singleList(const singleList &rhs)
{
eraseList(head);
init();
*this = rhs;
print();
contains(head);
}
void init()
{
theSize = 0;
head = new Node<Object>;
head->next = (Object)NULL;
}
void eraseList(Node<Object> *h)
{
Node<Object> *ptr = h;
Node<Object> *nextPtr;
while (ptr != (Object)NULL)
{
nextPtr = ptr->next;
delete ptr;
ptr = nextPtr;
}
}
int size()
{
return theSize;
}
void print()
{
int i;
Node<Object> *current = head;
for(i=0; i < theSize; ++i){
cout << current->data << " ";
current = current->next;
}
}
bool contains(int x)
{
Node<Object> *current = head;
for (int i = 0; i < theSize; ++i){
if (current->data == x){
return true;
}
current = current -> next;
}
return false;
}
bool add(Object x){
if(!contains(x)){
Node<Object> *new_node = new Node<Object>(x);
new_node->data = x;
new_node->next = head;
head = new_node;
//head->next = new_node;
theSize++;
return true;
}
return false;
}
bool remove(int x)
{
if(contains(x)){
Node<Object> *temp = head;
Node<Object> *prev = NULL;
if(temp != NULL && temp ->data == x){
head = temp->next;
delete temp;
return 0;
}else{
while(temp != NULL && temp->data != x){
prev = temp;
temp = temp->next;
}
if(temp ==NULL){
return 0;
}
prev->next = temp->next;
delete temp;
}
return true;
//theSize--;
}
return false;
}
private:
Node<Object> *head;
int theSize;
};
int main()
{
singleList<int> *lst = new singleList<int>();
lst->add(10);
lst->add(12);
lst->add(15);
lst->add(6);
lst->add(3);
lst->add(8);
lst->add(3);
lst->add(18);
lst->add(5);
lst->add(15);
cout << "The original linked list: ";
lst->print();
cout << endl;
lst->remove(6);
lst->remove(15);
cout << "The updated linked list: ";
lst->print();
cout << endl;
cout << "The number of node in the list: " << lst->size() << endl;
return 0;
}
so the output is supposed to be the following:
The original linked list: 5 18 8 3 6 15 12 10
The update linked list: 5 18 8 3 12 10
The number of node in the list: 6
my output gives the original linked list part but then gives a segmentation fault (core dumped) error. I am not sure where my code is wrong but i think it is in my remove().
Some help will definitely be appreciated.
on line 109 i needed to decrement size.
bool remove(int x)
{
if(contains(x)){
Node<Object> *temp = head;
Node<Object> *prev = NULL;
if(temp != NULL && temp ->data == x){
head = temp->next;
delete temp;
return 0;
}else{
while(temp != NULL && temp->data != x){
prev = temp;
temp = temp->next;
}
if(temp ==NULL){
return 0;
}
prev->next = temp->next;
delete temp;
theSize--;
}
return true;
//theSize--;
}
return false;
}
Answer after second update:
had to fix the remove()
#include <iostream>
using namespace std;
template <typename Object>
struct Node
{
Object data;
Node* next;
Node(const Object &d = Object(), Node *n = (Object)NULL) : data(d), next(n) {}
};
template <typename Object>
class singleList
{
public:
singleList() { init(); }
~singleList() { eraseList(head); }
singleList(const singleList &rhs)
{
eraseList(head);
init();
*this = rhs;
print();
contains(head);
}
void init()
{
theSize = 0;
head = new Node<Object>;
head->next = (Object)NULL;
}
void eraseList(Node<Object> *h)
{
Node<Object> *ptr = h;
Node<Object> *nextPtr;
while (ptr != (Object)NULL)
{
nextPtr = ptr->next;
delete ptr;
ptr = nextPtr;
}
}
int size()
{
return theSize;
}
void print()
{
int i;
Node<Object> *current = head;
for(i=0; i < theSize; ++i){
cout << current->data << " ";
current = current->next;
}
}
bool contains(int x)
{
Node<Object> *current = head;
for (int i = 0; i < theSize; ++i){
if (current->data == x){
return true;
}
current = current -> next;
}
return false;
}
bool add(Object x){
if(!contains(x)){
Node<Object> *new_node = new Node<Object>(x);
new_node->data = x;
new_node->next = head;
head = new_node;
//head->next = new_node;
theSize++;
return true;
}
return false;
}
bool remove(int x){
Node<Object> *pCur = head;
Node<Object> *pPrev = pCur;
while (pCur && pCur->data != x) {
pPrev = pCur;
pCur = pCur->next;
}
if (pCur==nullptr) // not found
return false;
if (pCur == head) { // first element matches
head = pCur->next;
} else {
pPrev->next = pCur->next;
}
// pCur now is excluded from the list
delete pCur;
theSize--;
return true;
}
private:
Node<Object> *head;
int theSize;
};
int main()
{
singleList<int> *lst = new singleList<int>();
lst->add(10);
lst->add(12);
lst->add(15);
lst->add(6);
lst->add(3);
lst->add(8);
lst->add(3);
lst->add(18);
lst->add(5);
lst->add(15);
cout << "The original linked list: ";
lst->print();
cout << endl;
lst->remove(6);
lst->remove(15);
cout << "The updated linked list: ";
lst->print();
cout << endl;
cout << "The number of node in the list: " << lst->size() << endl;
return 0;
}

C++ code working as intended on Linux but not on Windows

I do not know why this code breaks ,probably when adding new node, on Windows .Returns "Process returned -1073741819 (0xC0000005)"),it was compiled with GNU GCC.It works perfectly fine on Linux.
Also tested on geeksforgeeks ide , this is the link https://ide.geeksforgeeks.org/feo8SYMsFP.
When debugged, SIGSEGV is returned when adding node but I am not sure why..
For example, input : 1 10 1 11 then it breaks..
#include <iostream>
#include <stdlib.h>
struct Node
{
int key;
Node * left;
Node * right;
};
class binarySearchTree
{
private:
Node *root;
Node *newNode(int key)
{
Node *temp = new Node;
temp->left = temp->right = NULL;
temp->key = key;
return temp;
}
void traverse_inorder(Node *temp)
{
if (temp==NULL)
return;
traverse_inorder(temp->left);
std::cout <<"Current key: "<< temp->key << "\n";
traverse_inorder(temp->right);
}
void find(Node* temp,int key)
{
if (temp==NULL)
return;
find(temp->left,key);
if (temp->key == key)
std::cout <<"Key " << key << " found\n";
find(temp->right,key);
}
Node* minValueNode(Node* n)
{
Node* x = n;
while (x->left != NULL)
x = x->left;
return x;
}
Node* deleteNode(Node* temp, int key)
{
if (temp == NULL)
return temp;
if (key < temp->key)
temp->left = deleteNode(temp->left, key);
else if (key > temp->key)
temp->right = deleteNode(temp->right, key);
else
{
if (temp->left == NULL)
{
Node *x = temp->right;
delete temp;
return x;
}
else if (root->right == NULL)
{
Node *x = temp->left;
delete temp;
return x;
}
Node* x = minValueNode(temp->right);
temp->key = x->key;
temp->right = deleteNode(temp->right, x->key);
}
return temp;
}
void delete_tree(Node *temp)
{
if (temp == NULL)
return;
delete_tree(temp->left);
delete_tree(temp->right);
delete temp;
}
void traverse_postorder(Node* temp)
{
if (temp == NULL)
return;
traverse_postorder(temp->left);
traverse_postorder(temp->right);
std::cout <<"Current key: "<< temp->key << "\n";
}
void traverse_preorder(Node* temp)
{
if (temp == NULL)
return;
std::cout <<"Current key: "<< temp->key << "\n";
traverse_preorder(temp->left);
traverse_preorder(temp->right);
}
void add(int key)
{
if (root == NULL)
root = newNode(key);
else
{
Node *temp = root;
while (true)
{
if (temp->key > key)
{
if (temp->left == NULL)
{
temp->left = newNode(key);
break;
}
else
temp = temp->left;
}
else if (temp->key < key)
{
if (temp->right == NULL)
{
temp->right =newNode(key);
break;
}
else
temp = temp->right;
}
else
{
std::cout << "Key already added!\n";
break;
}
}
}
}
public:
binarySearchTree()
{
root = NULL;
}
~binarySearchTree()
{
delete_tree(root);
}
void _find(int key)
{
find(root,key);
}
void _del(int key)
{
root = deleteNode(root,key);
}
void _traverse_postorder()
{
traverse_postorder(root);
}
void _traverse_preorder()
{
traverse_preorder(root);
}
void _traverse_inorder()
{
traverse_inorder(root);
}
void _add(int key)
{
add(key);
}
};
int main()
{
binarySearchTree bst;
std::cout << "Binary Search Tree Menu (1-add key, 2-search key, 3-remove key, 4-traverse inorder, 5-traverse postorder, 6-traverse preorder, q-exit)\n";
char input;
do
{
std::cout << "Awaiting input ";
std::cin >> input;
int key;
switch(input)
{
case '1':
std::cout << "Enter key.. ";
std::cin >> key;
bst._add(key);
break;
case '2':
std::cout << "Enter key.. ";
std::cin >> key;
bst._find(key);
break;
case '3':
std::cout << "Enter key.. ";
std::cin>>key;
bst._del(key);
break;
case '4':
bst._traverse_inorder();
break;
case '5':
bst._traverse_postorder();
break;
case '6':
bst._traverse_preorder();
break;
}
}
while (input != 'q');
std::cout << "Deleting Binary Search Tree...\n";
return 0;
}
This code:
struct Node
{
int key;
Node * left;
Node * right;
};
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
return temp;
}
means that newNode returns pointer to node with indeterminate values for left and right. Instead these should be null pointers, (e.g. use new Node(); instead of new Node;).
On the original system it probably happened to get zeroed memory from the allocator so the problem didn't show up.

Delete Function on Binary Search Tree w/ Unidentified Type Error

A partner of mine and I are working on an assignment for a class of ours and we have ran into a problem with one our cpp files. The purpose of the assignment is to use a generic binary search tree to implement a student/faculty database. A problem we have run into is that when we try to compile we run into an error on our delete function for the binary search tree. It's telling me that the TreeNode struct I have to create my nodes is an undefined type. However, for the other methods we get no errors. It's specifically for the delete method. Here's some the code of the cpp file with the methods of the BST:
#include <iostream>
#include <cstdlib>
#include "BinarySearchTree.h"
using namespace std;
//template <class T> BST<T>::BST():root(NULL){}
template <class T>
void BST<T>::freeMemory(BST::TreeNode *node)
{
if(node == nullptr)
return;
freeMemory(node->left);
freeMemory(node->right);
delete node;
}
template <class T>
void BST<T>::insert(T value)
{
TreeNode *treeNode = NULL;
/*try
{
}
catch()
*/
TreeNode *temp = NULL;
TreeNode *prev = NULL;
temp = root;
while(temp)
{
prev = temp;
if(temp->data < treeNode->data)
temp = temp->right;
else
temp = temp->left;
}
if(prev == NULL)
root = treeNode;
else
{
if(prev->data < treeNode->data)
prev->right = treeNode;
else
prev->left = treeNode;
}
}
template<class T>
void BST<T>::print(TreeNode *root)
{
if(root == NULL)
return;
print(root->left);
cout << root->data << endl;
print(root->right);
}
template<class T>
void BST<T>:: print()
{
print(root);
}
template<class T>
void BST<t>:: deleteNode(TreeNode *n, T item)
{
bool found = false;
TreeNode *prev = nullptr;
TreeNode *current = n;
if(current == nullptr)
cout<<"There is nothing in your tree."<< endl;
return;
while(current != nullptr)
{
if(current->data == item)
{
found = true;
break;
}
else
{
prev = current;
if(item > (current->data))
current = current->right;
else
current = current->left;
}
}
if (!found)
{
cout << item <<" not in Tree."<< endl;
return;
}
if((current->left==nullptr && current->right!= nullptr || (current->left != nullptr && current->right == nullptr))
{
if(current->left == nullptr && current->right != nullptr)
{
if(prev->left == current)
{
prev->left = current->right;
delete current;
current = nullptr;
cout << item <<" has been removed from the tree. "<<endl;
}
else
{
prev->right = current->right;
delete current;
current = nullptr;
cout << item <<" has been removed from the tree. "<<endl;
}
}
else
{
if(prev->left == current)
{
prev->left = current->left;
delete current;
current = nullptr;
cout << item <<" has been removed from the tree. "<<endl;
}
else
{
prev->right = current->left;
delete current;
current = nullptr;
cout << item <<" has been removed from the tree. "<<endl;
}
}
return;
}
if(current->left == nullptr && current->right == nullptr)
{
if(prev->left == current)
prev->left = nullptr;
else
prev->right = nullptr;
delete current;
cout << item <<" has been removed from the tree. "<<endl;
return;
}
if(current->left != nullptr && current->right != nullptr)
{
TreeNode *check = current->right;
if((current->left == nullptr) && (current->right != nullptr))
{
current = check;
delete check;
current->right == nullptr;
cout << item <<" has been removed from the tree. "<<endl;
}
else
{
if((current->right)->left != nullptr)
{
TreeNode *leftCurrent;
TreeNode *leftCurrentprev;
leftCurrentprev = current->right;
leftCurrent = (current->right)->left;
while(leftCurrent->left != nullptr)
{
leftCurrentprev = leftCurrent;
leftCurrent = leftCurrent->left;
}
current->data = leftCurrent->data;
delete leftCurrent;
leftCurrentprev-?left == nullptr;
cout << item << " has been removed from the tree. "<<endl;
}
else
{
TreeNode *temp = current->right;
current->data = temp->data;
current->right = temp->right;
delete temp;
cout << item <<" has been removed from the tree. "<<endl;
}
}
return;
}
}
Again we have an Unknown identifier type of "TreeNode" that keeps coming up as an error which I'm confused about since it doesn't come up for any other methods.
Possible case sensitivity related Typo?
You have a small 't' where you need a capital 'T' in:
template<class T> void BST<t>:: deleteNode(TreeNode *n, T item)

I would like not to use root as global

Hello I am writing an avl tree and I have one issue . I am currently having a root as global since I use it in the class as well as in main , how can I write it without having it global?
struct avl_node {
int data;
struct avl_node *left;
struct avl_node *right;
}*root;
class avlTree {
public:
int 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 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 *rr_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->right;
parent->right = temp->left;
temp->left = parent;
return temp;
}
avl_node *ll_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->left;
parent->left = temp->right;
temp->right = parent;
return temp;
}
avl_node *lr_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->left;
parent->left = rr_rotation (temp);
return ll_rotation (parent);
}
avl_node *rl_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->right;
parent->right = ll_rotation (temp);
return rr_rotation (parent);
}
avl_node* 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* insert(avl_node *root, int value)
{
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;
}
void display(avl_node *ptr, int level)
{
int i;
if (ptr!=NULL)
{
display(ptr->right, level + 1);
printf("\n");
if (ptr == root)
cout<<"Root -> ";
for (i = 0; i < level && ptr != root; i++)
cout<<" ";
cout<<ptr->data;
display(ptr->left, level + 1);
}
}
void inorder(avl_node *tree)
{
if (tree == NULL)
return;
inorder (tree->left);
cout<<tree->data<<" ";
inorder (tree->right);
}
void preorder(avl_node *tree)
{
if (tree == NULL)
return;
cout<<tree->data<<" ";
preorder (tree->left);
preorder (tree->right);
}
void postorder(avl_node *tree)
{
if (tree == NULL)
return;
postorder ( tree ->left );
postorder ( tree ->right );
cout<<tree->data<<" ";
}
avlTree()
{
root = NULL;
}
};
int main()
{
int choice, item;
avlTree avl;
while (1)
{
cout<<"\n---------------------"<<endl;
cout<<"AVL Tree Implementation"<<endl;
cout<<"\n---------------------"<<endl;
cout<<"1.Insert Element into the tree"<<endl;
cout<<"2.Display Balanced AVL Tree"<<endl;
cout<<"3.InOrder traversal"<<endl;
cout<<"4.PreOrder traversal"<<endl;
cout<<"5.PostOrder traversal"<<endl;
cout<<"6.Exit"<<endl;
cout<<"Enter your Choice: ";
cin>>choice;
switch(choice)
{
case 1:
system("cls");
cout<<"Enter value to be inserted: ";
cin>>item;
root = avl.insert(root, item);
break;
case 2:
system("cls");
if (root == NULL)
{
cout<<"Tree is Empty"<<endl;
continue;
}
cout<<"Balanced AVL Tree:"<<endl;
avl.display(root, 1);
break;
case 3:
system("cls");
cout<<"Inorder Traversal:"<<endl;
avl.inorder(root);
cout<<endl;
break;
case 4:
system("cls");
cout<<"Preorder Traversal:"<<endl;
avl.preorder(root);
cout<<endl;
break;
case 5:
system("cls");
cout<<"Postorder Traversal:"<<endl;
avl.postorder(root);
cout<<endl;
break;
case 6:
exit(1);
break;
default:
system("cls");
cout<<"Wrong Choice"<<endl;
}
}
return 0;
}
You should not explicitly use the tree's root in main(), and generally outside the tree's methods. To achieve this just make the method
avl_node* insert(avl_node *where, int value)
private (or protected, at least) in a class and add a public interface:
void insert(int value)
{
root = insert(root, value);
}
Then in main you add items simply by calling
avlTree tree;
....
tree.insert(item);
EDIT to answer a question asked in a comment.
Functions like display, inorder etc. should be handled in the same way as insert: declare a public, parameterless function to launch the action and a protected method with a parameter to recursively perform it:
public:
void display() { display(root, 0); }
void inorder() { inorder(root); }
.....
protected:
void display(avl_node *node, int level)
{
if (node!=NULL)
{
display(node->right, level + 1);
if (node == root)
cout << "Root -> ";
else
cout << " ";
cout << setw(5*level) << "" << node->data << endl;
display(node->left, level + 1);
}
}
void inorder(avl_node *node)
{
if (node)
{
inorder (node->left);
cout << node->data << " ";
inorder (node->right);
}
}
then use:
tree.display();
tree.inorder();