-4

Adding an element to the AVL tree. Tree currently has no elements. I am trying to add one. Function add performs ok, except program freezes and ends in 2 secs when it comes to return new node(k). Why is that?

struct node 
{
    int key;
    unsigned char height;
    node *left;
    node *right;
    node(int k) {key = k; left = right = 0; height = 1;}
};
node *root;
node *add(node* p, int k)
{
    if(!p)
    {
        return new node(k);

    }
    if(k < p->key)
        p->left = add(p->left,k);
    else
        p->right = add(p->right,k);
    return balance(p);
}


int main()
{
    root = NULL;
    add(root, 10);
    printf("%d",root->key);
    return 0;
}

1 Answers1

2

Your function returns a value, and you want to use it. But you're not saving it anywhere. In particular, you seem to be expecting root to contain the new node. So you have to do:

root = add(root, 10);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Why should I? `printf` has return value but I may not use it. – user9393410 Jun 08 '18 at 02:14
  • Because you're trying to use `root->key`. If you don't reassign it, it still contains `NULL`. – Barmar Jun 08 '18 at 02:16
  • Your function does `return new node(k);`. If you don't assign the return value to something, how will you use it? – Barmar Jun 08 '18 at 02:17
  • @LilBItch So, you are obviously trying to use the return value, and claiming you may not use it at the same time? Don't lie to yourself. –  Jun 08 '18 at 02:21
  • @LilBItch `printf()` returns a value, but most of the time you don't care about it, so you can ignore it. But `add()` returns a value and you *do* care about it, so you can't ignore it. – Barmar Jun 08 '18 at 02:22