ich den folgenden binären Suchbaum (in C++) habe, und ich habe eine Frage zu einer bestimmten Codezeile:Binary Tree „Verhalten“
delete k;
Mein Code funktioniert, wenn ich diese Zeile entfernen, und ich verstehe nicht warum. Nach meinem Verständnis: die Daten von k wird in den Baum eingefügt und dann wird die Variable k gelöscht. Warum werden die Daten auch vom Baum gelöscht?
hier ist mein Code:
#include <iostream>
using namespace std;
struct nod
{
nod *st=NULL;
int info;
nod *dr=NULL;
int h;
nod *par=NULL; // par = "father"
};
struct avl
{
nod *rad=NULL; //rad = root;
void insert(nod *z) //INSERT
{
nod *y = NULL;
nod *x = rad;
while (x != NULL)
{
y = x;
if (z->info < x->info)
{
x = x->st; // st = left
}
else
{
x = x->dr; //dr = right
}
}
if (y == NULL)
{
rad = z;
}
else
{
if (z->info < y->info)
{
y->st = z;
}
else
{
y->dr = z;
}
}
z->par = y;
}
void inordine(nod *k)
{
if (k)
{
inordine(k->st);
cout << k->info<<"\t";
inordine(k->dr);
}
}
};
int main(void)
{
avl *arbore = new avl;
int el = 5;
arbore->rad=NULL;
while (el >= 0)
{
cout << "element\n";
cin >> el;
nod *k = new nod;
k->dr = NULL;
k->st = NULL;
k->par = NULL;
k->info = el;
arbore->insert(k);
delete k;
}
cout << "print inordine\n";
arbore->inordine(arbore->rad);
}