繁体   English   中英

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

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

我创建了一个具有三个值的二叉树,它们是整数zipCode,州的字符串和城市的字符指针。 我试图计算多少个城市(邮政编码)处于相同的州。 因此,我在下面编写了一个函数,但是没有用。(格式与输入的图片相同,图片中的输入文件相同)希望有人可以帮帮我。 在此处输入图片说明

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

您没有添加孩子返回的数字。 同样,如果您正在评估的节点没有您正在寻找的状态,则永远不会搜索您的右节点。 下面应该是一个修复程序。

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

您将忽略两次递归返回的所有值。 您也应该将其添加到count变量中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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