2017-02-15 68 views
0
/* 
Here is the piece of code causing segmentation fault 
*/ 

int search_for_data(T_NODE head, int data){ 
    while(head){ 
     if(head->data > data) 
      head = head->left; 
     if(head->data < data) 
      head = head->right; 
     else 
      return head->key; 
     } 
return -999999;// in case the node is not found 
} 

該代碼似乎是拋出少數值的分段錯誤,但其他人可以正常工作。我試圖尋找22,並有分段錯誤。二叉搜索樹中的分段錯誤

回答

2

有丟失else之前if:它評估

if(head->data > data) 
     head = head->left; 
    else if(head->data < data) /* this line */ 
     head = head->right; 
    else 
     return head->key; 

與原代碼的第一個if然後馬上第二,雖然head可能第一if後已經成爲NULL

+0

非常感謝! 這真的很有幫助! –