在 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"<为了触发树的删除,我们在根节点上调用删除,因为它的左右子树将被删除。
delete root;示例
让我们看看以下使用delete关键字删除二叉树的实现-
#include输出结果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"< leftChild = node1; root->rightChild = node2; node1->leftChild = node3; node1->rightChild = node4; delete root; return 0; } 上面的代码将产生以下输出-
8 is being deleted 10 is being deleted 4 is being deleted 6 is being deleted 2 is being deleted