插入有序二进制搜索树

时间:2012-03-14 20:23:17

标签: c++ function struct binary-search-tree

我在创建C ++函数时遇到问题,该函数会将项目插入按字母顺序排序的二叉树中。

插入功能应该像这样工作:提示用户输入一个数字。这个数字是指要输入多少本书。然后输入书的标题和网址(定义为结构),并根据标题的第一个字母按字母顺序将书插入树中。

我已经定义了这样一本书,其中标题和网址是字符数组:

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;
        ...
    }
}

我想我可能不得不声明某种指向树根的指针,但我不知道在哪里放它。而且我也意识到我需要编写一个单独的“搜索”函数,我将在这个插入函数中调用,以找到实际插入本书的位置,但我只是寻求帮助来完成这个插入函数。

2 个答案:

答案 0 :(得分:0)

遍历树是递归非常擅长的事情之一。

我要做的是编写一个递归函数,该函数接受子树和插入值,并将该值插入子树中的适当位置。

答案 1 :(得分:0)

  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
}

另外,您不希望在book函数的任何位置引用insert,您想要阅读p->titlep->url,否则您将删除任何内容您每次创建新book时都在bookNode

---------- NOTES ---------------
我强烈建议您不要使用char*,而是使用std::string代替:

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
相关问题