简体   繁体   中英

insert values into a binary search tree in C?

I have a .h file that contains my struct and I must NOT edit this file:

struct KnightTree 
{
    int key;
    int level; 
    int balance;            //will be used in AVL only, and be ignored in other cases.
    KnightTree* pLeftChild;
    KnightTree* pRightChild;
};

And a .cpp file that I write my code here, I've written a code to insert 2 values (key and level) into the BST:

void BSTinsert(KnightTree* tree, int k, int lvl)
{
    KnightTree* newnode;
    if (tree == NULL)
    {
        newnode->key=k;
        newnode->level=lvl;
        newnode->pLeftChild=NULL;
        newnode->pRightChild=NULL;
        tree = newnode;
    }
    else
    {
        if (tree->key > k)
            BSTinsert(tree->pLeftChild,k,lvl);
        else if (tree->key <= k)
            BSTinsert(tree->pRightChild,k,lvl);
    }
}

But when I run it, the console "thinks" itself for about 3 seconds and error pop-up said "exe has stop working" so I have to close the program . I think's simple but I'm kinda confused now... I'm using Visual C++ 6.0 (I have to use this old version...)

Thank you guys!

You have at least 2 major problems:

  1. You do not allocate memory for your newnode , so by addressing it you just create memory corruption.
  2. You do not attach your newly created node to the tree, assigning tree = newnode doesn't create the necessary link to the tree.

Proceed from fixing these 2 issues.

And one more thing: have you tried to actually debug it before posting the question here?

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