2016-07-20 8 views
1

정수 ZipCode, 상태 문자열 및 도시의 문자 포인터 인 세 가지 값을 갖는 이진 트리를 만들었습니다. 얼마나 많은 도시 (우편 번호)가 같은 주에 있는지 계산하려고합니다. 따라서 다음과 같은 함수를 작성했지만 작동하지 않습니다. (형식은 그림에 표시된 입력 파일과 동일합니다.) 누군가가 나를 도울 수 있기를 바랍니다. 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

두 재귀 모두에서 반환 된 값은 무시됩니다. 카운트 변수에도이를 추가해야합니다.

관련 문제