二叉树上的宽度优先搜索

Breadth First Search on a Binary tree

本文关键字:搜索 二叉树      更新时间:2023-10-16

我试图通过使用他/她的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);
}
char *temp;
temp=strncpy(temp,q.front()->ID,8);

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

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

用c++的方式做事要好得多:使用std::string,避免char指针和空终止符的混乱。