当前位置:  开发笔记 > 编程语言 > 正文

二进制搜索树的析构函数

如何解决《二进制搜索树的析构函数》经验,为你挑选了1个好方法。

我正在尝试为我的Binary Search Tree编写析构函数,并且我知道如何递归遍历该树,但是我不知道如何在析构函数中执行此操作,以便删除每个节点。

我的标题是:

struct Node;
typedef string TreeType;
typedef Node * TreePtr;

//Defines a Node
struct Node
{
    TreeType Info;
    int countDuplicates = 1;
    TreePtr Left, Right;
};

class Tree
{
public:
    //Constructor
    Tree();

    //Destructor
    ~Tree();

    //Retruns true if the tree is Empty
    bool Empty();

    //Inserts a Node into the tree
    bool Insert(TreeType);

    //Delete decides what type of delection needs to occur, then calls the correct Delete function
    bool Delete(Node * , Node * );

    //Deletes a leaf node from the tree
    bool DeleteLeaf(TreePtr, TreePtr);

    //Deletes a two child node from the tree
    bool DeleteTwoChild(TreePtr);

    //Deletes a one child node from the tree
    bool DeleteOneChild(TreePtr, TreePtr);

    //Finds a certain node in the tree
    bool Find(TreeType);

    //Calculates the height of the tree
    int Height(TreePtr);

    //Keeps a count of the nodes currently in the tree;
    void Counter();

private:

    //Prints the nodes to the output text file in order alphabetically
    void InOrder(ofstream &,TreePtr);

    //Defines a TreePtr called Root
    TreePtr Root;

    //Defines a TreePtr called Current
    TreePtr Current;

    //Defines a TreePtr called Parent
    TreePtr Parent;
};

我的构造函数是:

Tree::Tree()
{
    Root = NULL;
    Current = NULL;
    Parent = NULL;
}

有没有办法递归调用析构函数?如果没有,如何遍历每个节点将其删除。



1> John Zwinck..:
void Tree::DestroyRecursive(TreePtr node)
{
    if (node)
    {
        DestroyRecursive(node->left);
        DestroyRecursive(node->right);
        delete node;
    }
}

Tree::~Tree()
{
    DestroyRecursive(Root);
}

推荐阅读
Gbom2402851125
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有