gpt4 book ai didi

c++ - 二叉树析构函数的递归调用

转载 作者:太空狗 更新时间:2023-10-29 21:42:02 25 4
gpt4 key购买 nike

根据我的理解,这段二叉搜索树析构函数的代码有效:

~tree(){

remove(root);
}

void remove(node* root)
{
if (root == NULL) return;
remove(root->left);
remove(root->right);
delete root;
}

但是,我想知道以下对析构函数的调用是否有效?

~node(){
delete left;
delete right;
}

~tree(){
delete root;
}

我的理解是删除根节点会自动调用子节点并删除它们。这是一个正确的假设吗? 如果确实正确,验证析构函数是否正常工作的简单方法是什么?

{{这部分帖子是后来添加的}}

我这里用的是第二种方法。通过输出表达式验证,下面的代码似乎不起作用,因为我得到了一个删除输出(这似乎是针对根节点的)

struct node{

~node(){
delete left;
delete right;
}
};

class tree {
node* root;

public:

tree(){
root=NULL;
}

~tree(){
cout<<"Deleting: "<<endl;
delete root;
}

void insert (int x){};
}

int main(){

A.insert(12);A.insert(13);A.insert(10);

return 0;
}

这是我得到的输出:

 Deleting:

理想情况下,应该有 3 个这样的表达式,但我只得到 1 个。

最佳答案

是的,只要叶节点的 left 和 right 等于 nullptr,它就可以工作。

根据C++标准(5.3.5删除)

6 If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).

因此只有当节点不是空指针值时才会调用节点的析构函数。

如果您想检查析构函数是否确实在工作,那么只需在析构函数的主体中插入一个输出语句即可。

这是一个演示程序

#include <iostream>

struct node
{
node *next;
int x;
~node()
{
std::cout << "inside node: " << x << std::endl;
delete next;
}
};

void push_front( node **tree, int x )
{
node *n = new node;
n->x = x;
n->next = *tree;

*tree = n;
}

void clear( node **tree )
{
delete *tree;
*tree = nullptr;
}

int main()
{
node *tree = nullptr;

for ( int i = 0; i < 10; i++ ) push_front( &tree, i );

clear( &tree );
}

输出是

Compiled with /EHsc /nologo /W4
main.cpp

Compilation successful!

Total compilation time: 187ms

inside node: 9

inside node: 8

inside node: 7

inside node: 6

inside node: 5

inside node: 4

inside node: 3

inside node: 2

inside node: 1

inside node: 0

Total execution time: 734ms

关于c++ - 二叉树析构函数的递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27380859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com