gpt4 book ai didi

c++ - 二叉搜索树的析构函数

转载 作者:太空狗 更新时间:2023-10-29 23:44:12 25 4
gpt4 key购买 nike

我正在尝试为我的二叉搜索树编写析构函数,我知道如何递归循环遍历树,但我不知道如何在析构函数中执行此操作以便删除每个节点。

我的标题是:

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;
}

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

最佳答案

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

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

关于c++ - 二叉搜索树的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34170164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com