簡體   English   中英

C ++二進制搜索樹實現未添加每個元素

[英]C++ Binary Search Tree implementation does not add every element

我有一個BST的簡單C ++實現。 我只想按順序添加數字並打印出來。 問題是,在我嘗試添加的16個數字中,我只能添加12(省略了32、15、14和3)。 我的控制台的輸出如下所示:

在添加數字之前打印樹:
清單為空
密鑰32已被添加。
按鍵15已經添加。
按鍵14已經添加。
按鍵3已被添加。
加數字后按順序打印樹:
2 4 21 50 52 64 70 76 80 83 87 100
程序以退出代碼結束:0

#include <iostream>

using namespace std;
class BST {

private:

    struct node {
        int data;
        node * left;
        node * right;
    };

    node * root;

    void addLeafPrivate(int data, node * n);
    void printInOrderPrivate(node *);


public:

    BST();
    node * createLeaf(int data);
    void addLeaf(int data);
    void printInOrder();


};

int main() {

    int TreeKeys[16]= {50, 76, 21, 4, 32, 64, 15, 52, 14, 100, 83, 2, 3, 70, 87, 80};
    BST bst;

    cout << "Printing the tree before adding numbers: \n";
    bst.printInOrder();

    for (int i = 0; i < 16; i++) {
        bst.addLeaf(TreeKeys[i]);
    }

    cout << "Printing the tree in order after adding numbers: \n";

    bst.printInOrder();

    return 0;
}

BST::BST() {root = NULL;}

BST::node * BST::createLeaf(int data) {

    node * n = new node;

    n->data = data;
    n->right = NULL;
    n->left = NULL;


    return n;

}

void BST::addLeaf(int data) {
    addLeafPrivate(data, root);
}


void BST::addLeafPrivate(int data, node * n) {

    if (root == NULL) {
        root = createLeaf(data);
    }

    else if (data < n->data) { // add recursively on left left side.
            if (n->left != NULL){
            addLeafPrivate(data, n->left);
            }
            else { // if left is empty
                n->left = createLeaf(data);
            }
        }

        else if (data > root->data) { // add recursively on right left side.
            if (n->right != NULL) {
                addLeafPrivate(data, n->right);
            }
            else { // right is empty
                n->right = createLeaf(data);
            }


        }

    else {
        cout << "The key " << data << " has already been added.\n";
    }
}

void BST::printInOrder() {

    printInOrderPrivate(root);

}

void BST::printInOrderPrivate(node * n) {

    if (n != NULL) {

        if (n->left != NULL) {
            printInOrderPrivate(n->left);
        }
        cout << n->data << " ";

        if (n->right != NULL) {
            printInOrderPrivate(n->right);
        }


    }

    else {
        cout << "The list is empty\n";
    }


}
else if (data > root->data) { // add recursively on right left side.

應該

else if (data > n->data) { // add recursively on right left side.

問題開始於32 由於21已經剩下50 ,因此您的算法會認為已經插入了32 ,這是因為您執行root->data而不是正確的n->data ,而不是比較data值並引發異常。

因此:左右檢查是否為null ,比較data是大於還是小於,並檢查是否相等。 這樣做可以使您更輕松地找到這樣的錯誤。

暫無
暫無

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

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