在 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,因为它的左、右子树将一起被删除。
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 deleted 10 is being deleted 4 is being deleted 6 is being deleted 2 is being deleted
广告