3

たぶん何百万回も前に尋ねられましたが、私はこれの何が悪いのか理解できません。インターネットでコードを使いたくなかったので、頭の中にあるものをプログラムしようとしました。これまたは私の印刷機能のいずれかが間違っています。以下のコードに何か問題がありますか?

void addNode(int value)
    {
        Node* newNode=new Node;
        newNode->data=value;
        if(root==NULL)
            root=newNode;
        else {
            Node* temp=root,*parent;
            while(temp!=NULL)
            {
                parent=temp;
                if(temp->data == value)
                    return;
                else if(temp->data < value)
                    temp=temp->left;
                else 
                    temp=temp->right;
            }
            temp=newNode;
        }
    }
4

1 に答える 1

6
temp=newNode;

これにより、ポインタがローカル変数に割り当てられます。この変数は、関数が戻ったときに破棄され、新しいノードが失われます。代わりに、ツリー内のポインターに割り当てます。おそらく次のようなものです:

if (temp->data < value) {        // If the new node should be to the left
    if (temp->left) {            //   If there is a left subtree
        temp = temp->left;       //      Move into the left subtree
    } else {                     //   Otherwise
        temp->left = newNode;    //      Insert the new node there
        return;                  //      Done.
    }
}

同様にtemp->rightifの場合value < temp->data

また:

if (temp->data == value) 
    return;

そこにメモリリークがあります。delete newNode戻る前にすべきです。

于 2012-04-18T18:23:17.547 に答える