2016-07-20 7 views
1

整数zipCode、状態の文字列、都市の文字ポインタの3つの値を持つバイナリツリーを作成しました。私はいくつの都市(zipCodes)が同じ州にあるのかを数えようとしています。したがって、私は以下の関数を書いたが、うまくいきません。(形式は入力ファイルと同じですが、写真に掲載されています)誰かが私を助けてくれることを願っています。 enter image description hereノードがcharであるバイナリツリーの特定のノードを数えます。

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

これは機能しません - どのようにですか?そして再帰呼び出しの結果で何をやっているのですか? 'count'は呼び出しのすべてのインスタンスに対してローカルなので、何もないように見えます。 –

答えて

2

あなたの子供が返す数字は追加していません。また、評価しているノードに探している状態がない場合は、正しいノードが検索されません。以下は修正でなければなりません。

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

それは働いて、thx !! –

0

両方の再帰から返される値はすべて無視されます。 これをcount変数にも追加する必要があります。

関連する問題