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

来源:互联网 发布:jsp 引入js 加版本号 编辑:程序博客网 时间:2024/04/28 18:17
#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;
}
0 0
原创粉丝点击