在 C++ 中使用 delete 关键字删除二叉树?
让我们首先使用包含 int 数据的类 btree_node * rightChild, btree_node * leftChild 来定义我们的二叉树。leftChild 和 rightChild 是指向 btree_node 的指针。我们班的所有成员都是公开的。
class btree_node {public:
int data;
btree_node* leftChild;
btree_node* rightChild;
为了创建一个新节点,我们有一个构造函数,它将 int 值作为参数分配给新创建的节点值。leftChild 和 rightChild 设置为 null。
btree_node(int data){this->data = data;
this->leftChild = NULL;
this-> = NULL;
}
类解构器在调用时使用delete关键字删除二叉树的左右子树。
~btree_node(){delete leftChild;
delete rightChild;
cout << this->data << "is being deleted"<<endl;
}
为了触发树的删除,我们在根节点上调用删除,因为它的左右子树将被删除。
delete root;
示例
让我们看看以下使用 delete 关键字删除二叉树的实现 -
#include <iostream>输出结果using namespace std;
class btree_node {
public:
int data;
btree_node* leftChild;
btree_node* rightChild;
btree_node(int data){
this->data = data;
this->leftChild = NULL;
this->rightChild = NULL;
}
~btree_node(){
delete leftChild;
delete rightChild;
cout << this->data << " is being deleted"<<endl;
}
};
int main(){
btree_node* root = new btree_node(2);
btree_node* node1 = new btree_node(4);
btree_node* node2 = new btree_node(6);
btree_node* node3 = new btree_node(8);
btree_node* node4 = new btree_node(10);
root->leftChild = node1;
root->rightChild = node2;
node1->leftChild = node3;
node1->rightChild = node4;
delete root;
return 0;
}
上面的代码将产生以下输出 -
8 is being deleted10 is being deleted
4 is being deleted
6 is being deleted
2 is being deleted
以上是 在 C++ 中使用 delete 关键字删除二叉树? 的全部内容, 来源链接: utcz.com/z/347613.html