插入到有序二叉搜索树中 < >我在创建一个C++函数时遇到困难,它将把一个项目插入到按字母顺序排序的二进制树中。
insert函数的工作原理如下:提示用户输入一个数字。此数字表示要输入的图书数量。然后输入定义为结构的书籍的标题和url,并根据标题的第一个字母按字母顺序将书籍插入到树中 我定义了这样一本书,书名和url是字符数组:插入到有序二叉搜索树中 < >我在创建一个C++函数时遇到困难,它将把一个项目插入到按字母顺序排序的二进制树中。,c++,function,struct,binary-search-tree,C++,Function,Struct,Binary Search Tree,insert函数的工作原理如下:提示用户输入一个数字。此数字表示要输入的图书数量。然后输入定义为结构的书籍的标题和url,并根据标题的第一个字母按字母顺序将书籍插入到树中 我定义了这样一本书,书名和url是字符数组: struct bookNode { char title[30]; char url[40]; char key; bookNode *left; bookNode *right; } book; 这就是我到目前为止对于插入函数所做的: v
struct bookNode {
char title[30];
char url[40];
char key;
bookNode *left;
bookNode *right;
} book;
这就是我到目前为止对于插入函数所做的:
void insertBook () {
struct bookNode *p, *q;
int i, n;
char key;
cout << "Enter the number of books you want to add" << endl;
cin >> n;
for(i=0;i<n;i++) {
p = (struct bookNode *)malloc(sizeof(struct bookNode));
if(p==0)
cout << "Out of Memory" << endl;
cout << "Enter the title of the book" << endl;
cin.getline(book.title, 30);
key = book.title[0];
cout << "Enter the url of the book" << endl;
cin.getline(book.url, 40);
p->key; //I'm not sure if these next 3 lines are right
p->left=0;
p->right=0;
...
}
}
我在想,我可能还必须声明某种指向树根的指针,但我不确定该放在哪里。我还意识到我需要编写一个单独的搜索函数,我将在这个插入函数中调用它,以找到实际插入书籍的位置,但我只是在寻找帮助来完成这个插入函数。遍历树是递归非常擅长的事情之一
我要做的是编写一个递归函数,它接受一个子树和一个要插入的值,并将该值插入到子树中的适当位置每个节点有一个父指针是正常的。为什么在C++代码中使用MALOC?还有,你们为什么要把数据读入书中?@MooingDuck我不确定把数据读入书中是否正确。我只是不知道如何初始化一本书。我是新手:-/p是新书,所以cin.getlinep->title,30;?:P@MooingDuck好的,这是有道理的。谢谢。我要传递给递归函数的要插入的值,我也可以传递整个图书结构吗?@aclark你可以传递对图书结构的引用。然后你调用的搜索函数就是我比较标题的第一个字母的地方,对吗?哦,好的,我看到您比较了主函数中的字符串。@aclark:这只是std::string工作原理的一个示例,请不要在主函数中进行搜索:/
bookNode* closest = search(p); //find closest node to where p goes
if (p->key < closest->key) //if p goes to the left
closest->left = p; //put it on the left
else //otherwise
closest->right = p; //put it on the right
bookNode* search(bookNode* findme) {
//The search should traverse the tree
//and return a pointer to the "bottom" bookNode
//that is closest in value to p->title
}
struct bookNode {
std::string title; //unlimited space
//other members
} book;
int main() {
std::string name = "Fred"; //easy to make
std::getline(cin, name); //read in entire title, no matter how long
if (name < "Fred") //easy to compare entire strings
std::cout << name; //easy to use
} //deletes itself automagically