簡體   English   中英

插入有序二進制搜索樹

[英]Inserting into an Ordered Binary Search Tree

我在創建C ++函數時遇到麻煩,該函數會將項目插入按字母順序排序的二叉樹中。

插入功能應按以下方式工作:提示用戶輸入數字。 此數字將涉及要輸入的書籍數量。 然后輸入書名和URL(定義為結構),然后根據書名的第一個字母將書按字母順序插入樹中。

我已經定義了這樣的書,其中的標題和網址是字符數組:

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

我在想可能還必須聲明某種指向樹根的指針,但是我不確定將其放置在何處。 而且我還意識到我將需要編寫一個單獨的“搜索”函數,在該插入函數中調用該函數,以查找將書實際插入的位置,但是我只是在尋求幫助以完成此插入函數。

遍歷樹是遞歸最擅長的事情之一。

我要做的是編寫一個帶子樹的遞歸函數,並插入一個值,然后將該值插入子樹的適當位置。

  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
}

另外,您也不想在insert函數中的任何地方引用book ,您想讀入p->titlep->url ,否則每次創建一個新的bookNode時,您都將擦除book所有bookNode

- - - - - 筆記 - - - - - - - -
我強烈建議不要使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM