📜  使用 delete 关键字删除二叉树

📅  最后修改于: 2022-05-13 01:57:16.356000             🧑  作者: Mango

使用 delete 关键字删除二叉树

在之前的文章中已经讨论了删除整个二叉树的递归和非递归程序。在这篇文章中,讨论了在 C++ 中使用delete关键字删除整个二叉树。

在“BinaryTreeNode”类中声明一个析构函数,该类已定义为创建树节点。在类的对象上使用'delete'关键字会删除整个二叉树。它的析构函数在析构函数中被调用。对孩子使用“删除”关键字;所以孩子的析构函数会被一一调用,这个过程会递归进行,直到整个二叉树被删除。考虑下面显示的树,一旦为根调用析构函数,即“1”,它将调用“2”和“3”的析构函数,然后 2 将为其左右子节点调用相同的数据“4”和“5”分别。最终,树会按顺序被删除: 4->5->2->3->1 (后序)

以下是上述方法的 C++ 实现:

// C++ program to delete the entire binary
// tree using the delete keyword
#include 
using namespace std;
  
class BinaryTreeNode {
  
    // Making data members public to
    // avoid the usage of getter and setter functions
public:
    int data;
    BinaryTreeNode* left;
    BinaryTreeNode* right;
  
    // Constructor function to
    // assign data to the node
    BinaryTreeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
  
    // Destructor function to delete the tree
    ~BinaryTreeNode()
    {
        // using keyword to delete the tree
        delete left;
        delete right;
  
        // printing the node which has been deleted
        cout << "Deleting " << this->data << endl;
    }
};
  
// Driver Code
int main()
{
    // Creating the nodes dynamically
    BinaryTreeNode* root = new BinaryTreeNode(1);
    BinaryTreeNode* node1 = new BinaryTreeNode(2);
    BinaryTreeNode* node2 = new BinaryTreeNode(3);
    BinaryTreeNode* node3 = new BinaryTreeNode(4);
    BinaryTreeNode* node4 = new BinaryTreeNode(5);
  
    // Creating the binary tree
    root->left = node1;
    root->right = node2;
    node1->left = node3;
    node1->right = node4;
  
    // Calls the destructor function which actually deletes the tree entirely
    delete root;
  
    return 0;
}
输出:
Deleting 4
Deleting 5
Deleting 2
Deleting 3
Deleting 1