0

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!

4

1 回答 1

2

你至少有两个主要问题:

  1. 您没有为您的 分配内存newnode,因此通过解决它只会造成内存损坏。
  2. 您不会将新创建的节点附加到树上,分配tree = newnode不会创建到树的必要链接。

继续解决这两个问题。

还有一件事:在此处发布问题之前,您是否尝试过实际调试它?

于 2012-11-19T08:23:32.640 回答