简体   繁体   中英

counting the specific nodes in a binary tree in which the nodes are chars in c

I created a Binary tree that has three values which are integer zipCode, character strings of States, and character pointer of city. I'm trying to count how many cities (zipCodes) are in the same states. Therefore, I wrote a function in the following, but it doesn't work.(the format is as same as input file which is posted in here the picture) Hope someone can help me out. enter image description here

typedef struct n_ {
    int zipCode;   // A zip code that exists in the given city/state
    char *city;    // Will point to a city name
    char state[3]; // A state abbreviation. Note that we need
                   // room for the NULL terminator!
    struct n_ *left; //connections to other nodes
    struct n_ *right;
} Node;

int findStateCount(Node *root, char *state) {
    int count = 0;
    if (root!=NULL) {
        findStateCount(root->left, state);
        if (strcmp((root-> state), (state)) == 0)
            ++count;
        findStateCount(root->right, state);
    }
    return count;
}

You are not adding the numbers being returned by your children. Also if the node you are evaluating does not have the state you are looking for, your right node is never searched. Below should be a fix.

int findStateCount(Node* root, char* state){
           int count=0;
           if (root!=NULL){

               //Check if this node has the state we're looking for
               if(strcmp((root-> state),(state))==0)
                   ++count;
               }

               //Get the number of matches from my children
               count += findStateCount(root->left,state);
               count += findStateCount(root->right,state);
           }

           return count;
}

You are ignoring all values returned from both recursions. You should add it into count variable too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM