初识树结构,简单模拟无规律的二叉树,实现二叉树的构建,计算树的深度以及三种遍历方式以及搜索删除,销毁整个树

构建如图树结构:

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

运行结果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值