简体   繁体   中英

binary tree insert function

this isn't working, does this look right to you guys? I think the logic is right, but I could be totally wrong

anyone have any ideas?

This is just the insert function, it's only supposed to work for ints

void BST::Insert(int valueToInsert) {

    if (root == NULL) {
        root = new Node();
        root->val = valueToInsert;
        root->parent = NULL;
        root->left = NULL;
        root->right = NULL;

    } else {
        Node* tmp = new Node();
        tmp->val=valueToInsert;
        Node* trav = root;
        tmp->left=NULL;
        tmp->right=NULL;

        while (true) {   
            if((trav->val)>(trav->val)) {
                if (trav->right == NULL) {
                    trav->right = tmp;
                    tmp->parent = trav;
                    tmp->right = NULL;
                    tmp->left = NULL;                  
                    break;
                } else {
                    trav = trav->right;
                    continue;
            }
        }

        if ((tmp->val)<(trav->val)) {
            if (trav->left == NULL) {
                trav->left = tmp;        
                tmp->parent = trav;
                break;
            }else {
                trav = trav->left;
                continue;
            }
        }
    }        
}

The following looks suspicious:

           if((trav->val)>(trav->val)) {
               ^^^^        ^^^^

Was the first trav meant to be tmp ?

while (true) {


                if((trav->val)>(trav->val)) {

Right below the while condition trav->val is being compared to trav->val. This is not the intent, I guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM