二叉树上的宽度优先搜索
Breadth First Search on a Binary tree
我试图通过使用他/她的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
指针和空终止符的混乱。
相关文章:
- 从父数组测试用例构造二叉树失败
- 打印时有二叉树问题.用户输入不打印任何内容
- 试图找到二叉树的深度
- 按位置搜索,二叉树C++
- 给定的二叉树是否是二叉搜索树
- 程序设置二叉树,打印和搜索 - 节点类C++
- C++ 在不同类型的二叉树中搜索二叉树
- 我试图证明一个给定的树是一个二进制搜索树.我将输入一个二叉树,我只想让函数返回true
- 二叉树搜索的实现和函数声明c++
- 按键值搜索无序的二叉树
- 二叉树搜索不起作用
- 需要二叉树程序的帮助(不是二叉搜索树)
- 函数用于检查二叉树是否为二叉搜索树或是否工作
- 二叉树搜索没有返回期望的值
- 在对象的二叉树中搜索单个类成员
- 如何创建二叉树(不是二叉搜索树)
- 二叉树搜索不返回结果(c++)
- 二叉树搜索和跟踪
- 在二叉树中搜索
- 基于数据集合执行二叉树搜索