该函数不会向我的bst树添加任何内容

时间:2018-06-07 10:29:02

标签: c++ data-structures binary-search-tree

<span *ngIf="!slot.teiletyp.finished; else finishedPart" mat-line>
                Charge: {{ queue.box.batch_number }}
                </span>
                <ng-template #finishedPart>
                        <span mat-line >Fertigteilbox</span>
                        <mat-menu #menu="matMenu">
                        <button mat-menu-item (click)="boxClicked(queue.box)">boxdetail</button>
                        <button mat-menu-item (click)="openBoxes(queue.box.id)">offenebox</button>
                        </mat-menu>
                </ng-template>

我正在尝试使用上面的函数将数据插入到bst树中但它没有做任何事情,即使root是NULL 但是当我使用以下功能时,工作就完成了。我不明白我在两个代码中做了哪些不同的事情。我是编程新手,所以我有这么大的疑惑。请帮我清除它。

class node{
public:
    int data;
    node *left;
    node *right;
};

class BFStree{
public:
    void insert(int key);
    void deleteNode(int key);
    void inorderTraversal(node *temp);
    void inorder();
    node *root;
    BFStree(){
        root = NULL;
    }
};

 void BFStree::insert(int key){
    node *temp = root;
        while(temp!=NULL){
            if(key>temp->data){
                temp = temp->right;
            }
            else if(key<temp->data){
                temp = temp->left;
            }
            else{
                cout << "NOT ALLOWED TO HAVE SAME DATA" << temp->data << " " << key << endl;
            }
        }
        node *temp2 = new node;
        temp2->data = key;
        cout << key << " inserted" << endl;
        temp2->left = NULL;
        temp2->right = NULL;
        temp = temp2;
    }

int main(){
    BFStree t;
    t.insert(7);
    t.insert(3);
    t.insert(21);
}

1 个答案:

答案 0 :(得分:1)

你的第一个函数的主要问题是你只是迭代树直到你找到一个null,然后你将该值赋给temp。

之后,您将创建一个新节点并为temp节点分配新节点的引用。但是您的临时节点未连接到树。 temp节点与树的父节点或根节点之间没有连接。

而在第二个例子中:

if(temp->right==NULL){
            node *temp2 = new node;
            temp2->data = key;
            temp2->left = NULL;
            temp2->right = NULL;
            temp->right = temp2;
            break;
 }

这是关键,您将新创建的节点的引用存储在其父节点的右子节点中。