-1

So I wanted to make an AVL tree in C++. I used a class to make the nodes and a class for the rest of the fuctions (instert, delete etc). When I want to make more than one tree I decided that I needed to make more roots (one for every tree). The problem is when I declare the new root inside main. When I declare it outside it seems to work fine.

avlNode:

class avl_node
{
public:
    int data;
    avl_node *left;
    avl_node *right;
}*root;

avlTree::insert implementation:

avl_node* avlTree::insert(avl_node* root, int item)
{
    if (root == NULL) {
        root = new avl_node;
        root->data = item;
        root->left = NULL;
        root->right = NULL;
        return root;
    }
    if (item < root->data) {
        root->left = insert(root->left, item);
    }
    else if (item > root->data) {
        root->right = insert(root->right, item);
    }
    else if (item == root->data) {
        cout << "this exists" << endl;
    }
    root = balance(root);
    return root;
}

Main function:

int main()
{
    avl_node* roott;
    int item;   
    avlTree avl;
    avlTree kk;               
    root = avl.insert(root, item);          
    roott = kk.insert(roott, item);
    kk.display(roott, 1);
    return 0;
}
Beta Carotin
  • 1,659
  • 1
  • 10
  • 27
Jenny
  • 45
  • 8

1 Answers1

1
// in main
root = avl.insert(root, item);

// in avlTree::insert
avl_node* avlTree::insert(avl_node* root, int item) {
    if (root == NULL) { // <- Here

At Here, you are using ::root which is not initialized. At this point, ::root points to some random address, which is not what you want.

Write

}*root = NULL;

and

avl_node* roott = NULL;

to initialize those pointers.
You also need to initialize the int item in your main, presumably to 0.

int item = 0;
Beta Carotin
  • 1,659
  • 1
  • 10
  • 27