Question

Read a list of names from a file. Insert the names into a binary search tree that is a little different from what we discusse
Given the following names in the file: Dan, Phil, Angela, Ayesha, Kai, Zia, Troy, Troy. Troy. Dan Your tree would look like t
0 0
Add a comment Improve this question Transcribed image text
Answer #1

The C code for the given question is as follows:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct node //node to store the linked list details
{
    char name[30];
    struct node *next;
};

struct BinaryTree //BinaryTree to store the details of each node in the binary tree
{
    char name[30];
    struct node *names;
    struct BinaryTree *left;
    struct BinaryTree *right;
};

struct node *createTreeNode(char *n) //function to create new Tree node
{
    struct BinaryTree* temp = (struct BinaryTree *)malloc(sizeof(struct BinaryTree)); // allocate space for the node using malloc function
    strcpy(temp->name,n); //copy the name sent as parameter to the name variable in the Tree node
    temp->names = NULL; //assign names as null since Tree node will be created only for first occurrence of a name
    temp->left = NULL; //left pointer is assigned NULL
    temp->right = NULL; //right pointer is assigned NULL
    return temp;//return the created node
}

struct BinaryTree* insert(struct BinaryTree* root, char * name)
{
    if (root == NULL) //if the root is null it means that the tree is empty
        return createTreeNode(name); //therefore create a new node

    if(strcmpi(name,root->name)>0) //if the given name value is higher in order than root name value, we need to put it to the left side
        root->left = insert(root->left, name);// hence call the insert function recursively to insert node to the left side of root node
    else if(strcmpi(name,root->name)<0) //if the given name value is lower in order than root name value, we need to put it to the right side
        root->right = insert(root->right, name);// hence call the insert function recursively to insert node to the right side of root node
    else //otherwise it means that the name value is already present in the tree. Hence linked list associated with the tree node has to be updated
    {
        struct node* temp = (struct node *)malloc(sizeof(struct node)); //allocate memory for a node using malloc() function
        strcpy(temp->name,name); //copy the name sent as parameter to the name variable in the node
        temp->next = NULL; //make next pointer NULL
        struct node *t = root->names; // we need to attach it to the node with same name value as input given
        //Hence consider the names list of the node
        if(t==NULL)//if it is null
        {
            root->names = temp; //attach the newly created list node to the tree node
        }
        else
        {
            while(t->next!=NULL) // parse the list until we get the last list node
            {
                t = t->next;
            }
            t->next = temp; //attach the newly created list node to the end of the list
        }
    }
    return root; // return the root node
}

void searchPath(struct BinaryTree *root,char *name) //function to search for a name in the tree
{
    int count;
    if(root==NULL)
        printf("Name not found\n");
    else
    {
        printf("%s",root->name); // print the root node value everytime to generate the search path
        if(strcmpi(name,root->name)>0) // if name to be searched is larger than the root name
        {
            printf("-->"); // followed by --->
            searchPath(root->left, name); //search to the left
        }
        else if(strcmpi(name,root->name)<0) // if name to be searched is smaller than the root name
        {
            printf("-->"); //followed by --->
            searchPath(root->right, name); //search to the right
        }
        else // else it means it is found
        {
            count = 1; // 1 corresponds to value present in the node key
            struct node *t = root->names; //extract the root->names list
            while(t!=NULL) //parse the list to count the number of occurrences
            {
                count++; //increase count everytime until the end of list is reached
                t = t->next;
            }
            if(count>1) //if count is greater than 1, print the number of occurrences
                printf("\nThe count of occurrence for %s is %d\n",name,count);
        }
    }
}

int main()
{
    char ch;
    char namelist[200],search[30];//string arrays
    int i=0;
    struct BinaryTree *root = NULL;//create an empty binary tree
    FILE *fp = fopen("names.dat","r"); //open the file containing names in read mode
    ch = fgetc(fp);
    while(ch!=EOF)// read character from the file until the end of file is reached
    {
        namelist[i] = ch; // add the characters to the string namelist
        ch = fgetc(fp);
        i++; //increment index counter
    }
    namelist[i]='\0'; //terminate the string with null character
    char *filenames = strtok(namelist,","); // use strtok() to tokenize the namelist based on ','
    while(filenames!= NULL ) { // for each of the name found in the file
        root = insert(root,filenames); //insert it to the binary tree
        filenames = strtok(NULL, ","); // find the next name
    }
    printf("Enter the name you want to search: "); //ask for user to enter the name to be searched
    gets(search);
    printf("The search Path for %s is: ",search);
    searchPath(root,search); // call the searchPath function to display the path and occurrence
    fclose(fp); //close the file
    return 0;
}

#include<stdio.h> #include<stdlib.h> #include<string.h> struct node //node to store the linked list details char name[30]; st

if (root == NULL) //if the root is null it means that the tree is empty return createTreeNode (name); //therefore create a

void searchPath(struct BinaryTree *root, char *name) //function to search for a name in the tree { int count; if(root==NULL)

WN int main() char ch; char namelist [200], search [30]; //string arrays int i=0; struct BinaryTree root = NULL; // create an

OUTPUT:

Enter the name you want to search: Kai The search Path for kai is: Dan-->Phil.->Kai Process returned @ (@xo_execution time :

Enter the name you want to search: Troy The search Path for Troy is: Dan-->Phil-->Zia-->Troy The count of occurrence for Troy

Add a comment
Know the answer?
Add Answer to:
Read a list of names from a file. Insert the names into a binary search tree...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Need this in C++ Goals: Your task is to implement a binary search tree of linked...

    Need this in C++ Goals: Your task is to implement a binary search tree of linked lists of movies. Tree nodes will contain a letter of the alphabet and a linked list. The linked list will be an alphabetically sorted list of movies which start with that letter. MovieTree() ➔ Constructor: Initialize any member variables of the class to default ~MovieTree() ➔ Destructor: Free all memory that was allocated void printMovieInventory() ➔ Print every movie in the data structure in...

  • Using C Please comment Part 1: BST Create a link based Binary Search tree composed of a Node and a Tree struct. You should have a header file, BST.h, with the following: o Node struct containing...

    Using C Please comment Part 1: BST Create a link based Binary Search tree composed of a Node and a Tree struct. You should have a header file, BST.h, with the following: o Node struct containing left, right, and parent pointers, in addition to holding an Data struct value Tree struct containing a pointer to the root of the tree A function declaration for a function that allocates a tree, and initializes the root to NULL o o o A...

  • In C++ Given a pointer to the root of a binary search tree (has left, right,...

    In C++ Given a pointer to the root of a binary search tree (has left, right, and parent pointers as well as a data section ) write a function (or functions) which will return an STL list (you should not define this class, it’s already included) with all of the values from the tree in sorted order. Your code should run in theta(N) time. for the second part,.given a pointer to the first node of a linked list, you are...

  • SortAndSearch.cpp – Objectives: Binary Search and Selection sort You are given a list of 20 names...

    SortAndSearch.cpp – Objectives: Binary Search and Selection sort You are given a list of 20 names as follows: {"Collins, Bill", "Smith, Bart", "Michalski, Joe", "Griffin, Jim",                         "Sanchez, Manny", "Rubin, Sarah", "Taylor, Tyrone", "Johnson, Jill",                         "Allison, Jeff", "Moreno, Juan", "Wolfe, Bill", "Whitman, Jean",                         "Moretti, Bella", "Wu, Hong", "Patel, Renee", "Harrison, Rose",                   "Smith, Cathy", "Conroy, Pat", "Kelly, Sean", "Holland, Beth"}; Write a program to sort and display the names in alphabet order (use selection sort). The program prompts...

  • ASSIGNMENT DUE DATE GOT PUSHED BACK TO LATE THIS WEEK. PLEASE READ COMMENTS AND CODE BEFORE...

    ASSIGNMENT DUE DATE GOT PUSHED BACK TO LATE THIS WEEK. PLEASE READ COMMENTS AND CODE BEFORE ANSWERING CODING SECTIONS HW07 #Q1-Q5 HW08 #Q1-Q2 // READ BEFORE YOU START: // Please read the given Word document for the project description with an illustrartive diagram. // You are given a partially completed program that creates a list of students for a school. // Each student has the corresponding information: name, standard, and a linked list of absents. // Please read the instructions...

  • Hi there, I am working on a binary search tree code in c++. The program must...

    Hi there, I am working on a binary search tree code in c++. The program must store and update students' academic records, each node includes the student name, credits attempted, credits earned and GPA. I have made some progress with the code and written most of the functions in the .cpp file (already did the .h file) but i am struggling with what to put in the main and how to put an update part in the insert function. I...

  • // CSE240 Spring 2019 HW 7 & 8 // Write your name here // Write the...

    // CSE240 Spring 2019 HW 7 & 8 // Write your name here // Write the compiler used: Visual studio or gcc // READ BEFORE YOU START: // You are given a partially completed program that creates a linked list of patient information. // The global linked list 'list' is a list of patients with each node being struct 'patientList'. // 'patientList' consists of struct 'patient' which has: patient name, room number, and a linked list of 'doctors'. // The...

  • // C code // If you modify any of the given code, the return types, or...

    // C code // If you modify any of the given code, the return types, or the parameters, you risk getting compile error. // Yyou are not allowed to modify main (). // You can use string library functions. #include <stdio.h> #include <stdlib.h> #include <string.h> #pragma warning(disable: 4996) // for Visual Studio #define MAX_NAME 30 // global linked list 'list' contains the list of patients struct patientList {    struct patient *patient;    struct patientList *next; } *list = NULL;  ...

  • C++ Binary Search Tree question. I heed help with the level 2 question please, as level...

    C++ Binary Search Tree question. I heed help with the level 2 question please, as level 1 is already completed. I will rate the answer a 100% thumbs up. I really appreciate the help!. Thank you! searching.cpp #include <getopt.h> #include <iostream> #include <sstream> #include <stdlib.h> #include <unistd.h> using namespace std; // global variable for tree operations // use to control tree maintenance operations enum Mode { simple, randomised, avl } mode; // tree type // returns size of tree //...

  • C++ Binary Search Tree question. I heed help with the level 2 question please, as level...

    C++ Binary Search Tree question. I heed help with the level 2 question please, as level 1 is already completed. I will rate the answer a 100% thumbs up. I really appreciate the help!. Thank you! searching.cpp #include <getopt.h> #include <iostream> #include <sstream> #include <stdlib.h> #include <unistd.h> using namespace std; // global variable for tree operations // use to control tree maintenance operations enum Mode { simple, randomised, avl } mode; // tree type // returns size of tree //...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT