【问题标题】:counting the specific nodes in a binary tree in which the nodes are chars in c计算二叉树中的特定节点,其中节点是 c 中的字符
【发布时间】:2016-11-24 05:36:40
【问题描述】:

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

【问题讨论】:

  • 它不起作用 - 怎么办?你对递归调用的结果做了什么?看起来什么都没有,因为 count 对于每个调用实例都是本地的。

标签: c recursion binary-tree


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 2021-01-02
      • 1970-01-01
      • 2020-03-23
      • 2020-02-21
      • 1970-01-01
      相关资源
      最近更新 更多