0

If i have for example 2 binary trees:

typedef struct node {
    int key;
    struct node *left, *right;
} node;

node* root1
node* root2

I've tried this function to insert nodes:

void insert(node* root, int key) {
    node *p, *q;
    p = (node*) calloc(1,sizeof(node);
    p->key = key;
    if (root == NULL) {
        root = p;
        return;
    }
    q = root;
    for (;;) {
        if (key < q->key) {
            if (q->left == 0) {
                q->left = p;
                return;
            } else q = q->left;
        } else if (key > q->key) {
            if (q->right == 0) {
                q->right = p;
                return;
            } else q = q->right;
        } else {
            free(p);
            return;
        }
    }
}

but after call insert(root1,10) the tree root1 remains untouched. I suppose it happens because root variable inside function is changed locally.

How i should implement the function that will receive as argument the tree in which i want to insert nodes?

3
  • 1
    Right, to have a change the pointer itself reflected on the outside you'll need to pass it in as a double-pointer (**). Commented May 3, 2021 at 16:17
  • Compile your C code with GCC invoked as gcc -Wall -Wextra -g then use valgrind and the GDB debugger to understand the behavior of your program. Read Modern C and the documentation of your compiler and debugger. Be aware that StackOverflow is not a do-my-homework website Commented May 3, 2021 at 16:21
  • Read also about read-black trees and study for inspiration the source code of Glib Commented May 3, 2021 at 16:24

1 Answer 1

2

You could always return a pointer to the root, like this

node* insert(node* root, int key) {
    node *p, *q;
    p = (node*) calloc(1,sizeof(node));
    p->key = key;
    if (root == NULL) {
        root = p;
        return root;
    }
    q = root;
    for (;;) {
        if (key < q->key) {
            if (q->left == 0) {
                q->left = p;
                return root;
            } else q = q->left;
        } else if (key > q->key) {
            if (q->right == 0) {
                q->right = p;
                return root;
            } else q = q->right;
        } else {
            free(p);
            return root;
        }
    }
}

And you create your tree like -

node* root1 = NULL;
root1 = insert(root1,3)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.