Search code examples
cpointersbinary-search-treenodesreturn-value

Failed to receive a node pointer's value when returning it from a function


So this is my search function in the Binary Search Tree.

When returning the result node to my insert function, a variable in insert function cannot receive the value returned from search function.

typedef struct tree_node {
    struct tree_node *left_child;
    struct tree_node *right_child;
    int data;
    int level;
} Node;

typedef Node* Tree;
Tree searchPoint(Tree node, int key)
{
    if (node == NULL || key == node->data) {
        return node;
    }
    if (key < node->data) {
        return searchPoint(node->left_child, key);
    }
    if (key > node->data) {
        return searchPoint(node->right_child, key);
    }
    return node;

}
Tree insert(Tree root, int key, Tree head)
{

    Tree ptr, newNode;
    newNode = (Tree)malloc(sizeof(Node*));
    ptr = (Tree)malloc(sizeof(Node*));
    if (root == NULL) {
        newNode->data = key;
        if (head == NULL) {
            newNode->level = 1;
        }
        else {
            ptr = searchPoint(head, key);
            newNode->level = ptr->level + 1;
        }
        newNode->left_child = newNode->right_child = NULL;
        return newNode;
    }

    if (key < root->data) {
        root->left_child = insert(root->left_child, key, head);
    }
    else if (key > root->data) {
        root->right_child = insert(root->right_child, key, head);
    }

    return root;
}

I have tried to debugging line by line, I can clearly see a node value when returning in searchPoint(). However, back into insert function, variable ptr receive a NULL pointer.

I can't figure this out, can anyone help me out?

Also, the main function here

int main()
{
    int n, key;
    Tree root = NULL;
    Tree head = NULL;
    printf("Input the number of integers:\n");
    scanf("%d", &n);
    printf("Input these integers:\n");
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &key);
        root = insert(root, key, head);
        if (i == 0) {
            head = root;
        }
    }

    print_level(head);
    return 0;
}

Solution

  • I have solved this by returning NULL instead of node itself

    Tree searchPoint(Tree node, int key)
    {
        if (!node || (key == node->data)) {
            return NULL;
        }