广度优先搜索二叉树

时间:2011-12-22 17:33:12

标签: c++ binary-tree breadth-first-search

我正在尝试遍历二叉树,通过使用他/她的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);

}

1 个答案:

答案 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并避免所有这些与char指针和空终止符混淆。

相关问题