Search code examples
crecursionsearchbinary-search-treefunction-definition

Search function with multiple data type in C binary search tree


I have a BST with id as a key as follows:

struct node
{
    int id;
    char name[100];
    struct node *right;
    struct node *left;
};

Here is the code to search an id:

struct node* search(struct node *root, int x)
{
    if(root==NULL || root->id==x)
        return root;
    else if(x>root->id)
        return search(root->right, x);
    else
        return search(root->left,x);
}

But what if I want to search for a name? Is it possible? Any suggestion? Thanks


Solution

  • As the binary tree is ordered based on the key int id then you need to traverse all nodes of the tree to find a node with the specified name using the string function strcmp.

    For example

    #include <string.h>
    
    //...
    
    struct node* search(struct node *root, const char *name )
    {
        if(root==NULL || strcmp( root->name, name ) == 0 )
        {
            return root;
        }
        else 
        {
            struct node *target = search(root->left, name);
            return target != NULL ? target : search(root->right, name);
        }
    }