数据结构——二叉树的孩子链表表示法

本文介绍了一个使用C++实现的复杂树形数据结构,包括创建与遍历树节点的过程。通过用户输入定义树的结构,并实现了深度优先遍历算法来展示树的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<malloc.h>
#include<iostream>
#include<string.h>
#define null 0
using namespace std;
#define MAXSIZE 100
#define MAXENTERSIZE 30
#define null 0
typedef struct CTNode
{
int child;
struct CTNode *next;
}*ChildPtr;
typedef struct CTBox
{
char data;
ChildPtr firstchild;
}CTBox;
typedef struct CTree
{
CTBox nodes[MAXSIZE];
int r;
int n;
}CTree;
void CreateTree(CTree &CT)
{
char s[MAXSIZE];
cout<<"请输入二叉树的结点元素"<<endl;
gets(s);
CT.n=strlen(s);
int i;
for(i=0;i<CT.n;i++)
CT.nodes[i].data=s[i];
for(i=0;i<CT.n;i++)
{
CTNode *T=(CTNode*)malloc(sizeof(CTNode));
T->next=null;
T->child=0;
CTNode *rear=CT.nodes[i].firstchild=T;
cout<<"请输入"<<s[i]<<"元素的孩子结点:"<<endl;
char m[MAXENTERSIZE];
gets(m);
for(int j=0;j<strlen(m);j++)
{
int g;
for(g=0;g<CT.n;g++)
{
if(m[j]=='#')
break;
if(m[j]!=s[g])
continue;
else
{
CTNode *newbase=(CTNode *)malloc(sizeof(CTNode));
if(!newbase)
cout<<"ERROR\n";
newbase->next=null;
newbase->child=g;
rear->next=newbase;
rear=newbase;
}
}
}
}
}
void TraverseTree(CTree CT)
{
int i;
bool tof[MAXENTERSIZE];
for(i=0;i<CT.n;i++)
tof[i]=false;
for(i=0;i<CT.n;i++)
{
if(tof[i]==false)
{
tof[i]=true;
cout<<CT.nodes[i].data;
}
CTNode *p=CT.nodes[i].firstchild->next;
while(p!=null)
{
if(tof[p->child]==false)
{
tof[p->child]=true;
cout<<CT.nodes[p->child].data<<"\t";
}
p=p->next;
}
}
}
int main()
{
CTree CT;
CreateTree(CT);
TraverseTree(CT);
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值