构建如图树结构:
#include<iostream>
#include <tchar.h>
using namespace std;
struct Tree//树基本结构体
{
TCHAR data;
struct Tree* Lnode;
struct Tree* Rnode;
};
Tree* CreateTree(Tree* & tree,TCHAR data)//创建节点
{
if (!tree)
{
tree = new Tree;
tree->data = data;
tree->Lnode = NULL;
tree->Rnode = NULL;
}
return tree;
}
void RemoveTree(Tree * & tree ,TCHAR DATA)//删除节点(只能一个分支的删除)
{
if (tree)
{
RemoveTree(tree->Lnode, DATA);
RemoveTree(tree->Rnode, DATA);
if (tree->data == DATA)
{
delete tree;
tree = NULL;
}
}
}
void TraverseTree(Tree* tree,char h)
{
if (tree)
{
switch (h)
{
case 1://前序遍历
printf("%c ", tree->data, h);
TraverseTree(tree->Lnode, h);
TraverseTree(tree->Rnode, h);
break;
case 2://中序遍历
TraverseTree(tree->Lnode, h);
printf("%c ", tree->data, h);
TraverseTree(tree->Rnode, h);
break;
case 3://后序遍历
TraverseTree(tree->Lnode, h);
TraverseTree(tree->Rnode, h);
printf("%c ", tree->data, h);
break;
}
}
}
void DestoryTree(Tree* tree)//销毁树
{
if (tree)
{
DestoryTree(tree->Lnode);
DestoryTree(tree->Rnode);
delete tree;
tree = NULL;
}
}
int DeptchTree(Tree* & tree)//计算树的深度
{
int Ldeptch, Rdeptch, deptch;
Ldeptch = Rdeptch = deptch = 0;
if (tree)
{
Ldeptch = DeptchTree(tree->Lnode);
Rdeptch = DeptchTree(tree->Rnode);
deptch = Ldeptch > Rdeptch ? Ldeptch : Rdeptch;
return deptch + 1;
}
else
return 0;
}
int main()
{
Tree*a = NULL;
//模拟树的生成
CreateTree(a, 'A');
CreateTree(a->Lnode, 'B');
CreateTree(a->Lnode->Rnode, 'C');
CreateTree(a->Rnode, 'D');
CreateTree(a->Rnode->Rnode, 'E');
CreateTree(a->Rnode->Rnode->Lnode, 'F');
cout << "树的深度为:"<<DeptchTree(a) << endl;
TraverseTree(a, 1);
cout << "前序遍历" << endl;
TraverseTree(a, 2);
cout << "中序遍历" << endl;
TraverseTree(a, 3);
cout << "后序遍历" << endl;
//删除
RemoveTree(a, 'B');
RemoveTree(a, 'F');
cout << "删除B和F后:"<< endl;
TraverseTree(a,1);
cout << "前序遍历" << endl;
TraverseTree(a, 2);
cout << "中序遍历" << endl;
TraverseTree(a, 3);
cout << "后序遍历" << endl;
//销毁整个树
DestoryTree(a);
system("pause");
return 0;
}
运行结果如下: