二叉树 "behavior"

Binary Tree "behavior"

我有以下二叉搜索树(在 C++ 中),我对特定代码行有疑问:

delete k;

如果我删除该行,我的代码可以正常工作,但我不明白为什么。 据我了解:来自 k 的数据被插入到树中,然后变量 k 被删除。 为什么数据也从树中删除?

这是我的代码:

#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);


}

the data from k is being inserted into the tree and THEN then the variable k is deleted

不,k只是一个指针。它指向点头(e)。您正在将此节点插入到您的树中(通过将其作为指针传递)。它不是副本,它是同一个节点。 delete 不会删除变量,它会删除节点,因此您也将其从树中删除。

反对像您正在使用的原始指针的一个重要论点是,很难表达谁是对象的所有者。这是支持该论点的证据。你期望树拥有它的节点,你的程序显示相反的行为。

要正确处理节点,您需要一个遍历树并在树被破坏时删除每个节点的析构函数。您还需要通过使用像 avl::insert(int info, int h);

这样的插入来隐藏树用户的实际节点