2011-12-22 31 views
2

我正在尝试遍历二叉树以使用他/她的ID号找到某人的ID。当我调试这个功能时效果很好,但另一方面,当我直接运行时,它会自行终止。有人能解决它吗?在二叉树上的宽度优先搜索

struct person{ 
char ID[15]; 
char name[30] ; 
char surname[30]; 
person *left; 
person *right; 
}; 

struct tree{ 
person *root; 
void bfsSearch(); 
void BFS(person*,char*); 
}; 

void tree::BFS(person *root,char *search) 
//BFS traversal on a binary tree 
{ 
    char *temp; 
    std::deque<person *> q; 
    q.push_back(root); 
temp=strncpy(temp,q.front()->ID,8); 
while (q.size() != 0) 
{ 
    person *next = q.front(); 

    if (strcmp(search,temp)==0) 
    { 
     cout<<"Result: "<<q.front()->ID<<endl; 
     break; 
    } 
    q.pop_front(); 

    if (next->left) 
     q.push_back(next->sol); 
    if (next->right) 
     q.push_back(next->sag); 
    temp=strncpy(temp,q.front()->ID,8); 
    } 
} 

void tree::bfsSearch() 
{ 
    person *scan; 
    char *data,*temp; 
    data=new char[15]; 
    scan=root; 
    cout<<"Enter the Person`s ID to search: ";cin>>data; 
    BFS(root,data); 

} 
+0

root在哪里申报? – Pubby

+0

我更新了... –

回答

1
char *temp; 
temp=strncpy(temp,q.front()->ID,8); 

您将数据复制到一个未初始化的指针,这是不确定的行为。您需要将temp声明为一个数组,或者动态分配它。由于您只能复制最多8个字节,因此使用char temp[9];就足够了。请注意,如果输入过长,strncpy会使字符串不终止,因此您需要添加temp[8]=0;以保证安全。

strncpy的结果返回给temp也没有意义,因为它只是返回它的第一个参数。

用C++的方式做事情要好得多:使用std::string,避免所有这些与指针和空终止符相关的问题。

+0

我做到了,仍然一样。但奇怪的是,当我搜索位于根的右侧的ID号码时,它工作得很完美。它会发生错误,当我尝试搜索根的左侧 –