# 二进制搜索树的析构函数

##### 问题描述投票：2回答：4

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

c++ destructor
##### 4个回答
5

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

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

3

``````Tree::~Tree()
{
delete Root;
}
``````

``````Node::~Node()
{
delete Left;
delete Right;
}
``````

1

``````#include <iostream>
using namespace std;

class Node {
Node *left, *right;
public:
Node(Node *l, Node *r);
~Node();
};

class Tree {
Node *root;
public:
Tree(Node *rt);
~Tree();
};

Tree::Tree(Node *rt):root(rt) {
cout << "new Tree with root node at " << rt << endl;
}
Tree::~Tree() {
cout << "Destructor of Tree" << endl;
if (root) delete root;
}
Node::Node(Node *l, Node *r):left(l), right(r) {
cout << "Node@"
<< this
<< "(left:" << l
<< ", right:" << r << ")"
<< endl;
}
Node::~Node() {
cout << "~Node@" << this
<< endl;
if (left) delete left;
if (right) delete right;
}

int main() {
Tree t(
new Node(
new Node(
new Node(
new Node(0, 0),
0),
0),
new Node(0, new Node(0, 0))));
}
``````

0

``````struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
~TreeNode() {
delete left;
delete right;
}
...
};
``````

``````TreeNode* root = new TreeNode(2);
delete root;
``````