计算二叉树中的特定节点,其中节点是 c 中的字符

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

我创建了一个二叉树,它具有三个值,分别是整数 zipCode、州的字符串和城市的字符指针。我试图计算有多少个城市(邮政编码)处于相同的状态。因此,我在下面写了一个函数,但它不起作用。(格式与此处发布的输入文件相同图片)希望有人能帮助我。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;
}

您忽略了从两个递归返回的所有值。 您也应该将其添加到计数变量中。

您没有添加 children 返回的数字。此外,如果您正在评估的节点没有您正在寻找的状态,则永远不会搜索您的正确节点。下面应该是一个修复。

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;
}