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

时间:2022-05-27 12:59:57
#include <iostream>
using namespace std;

#define MAX_TREE_SIZE 100
typedef struct Cnode //孩子节点
{
char child;
struct Cnode * next;
}* CNode;
typedef struct
{
char data;
int parent; //双亲位置域
CNode firstchild; //孩子链表头指针
}PTNode;
typedef struct //树结构
{
PTNode node[MAX_TREE_SIZE];
int count; //节点个数
}CTree;

//初始化树
void init_ptree(CTree &tree)
{
tree.count=-1;
int i;
for(i=0;i<MAX_TREE_SIZE;i++)
tree.node[i].firstchild=NULL;
}
//添加节点
void add_ptnode(CTree &tree, PTNode ptnode)
{
tree.count++;
tree.node[tree.count].data = ptnode.data;
tree.node[tree.count].parent = ptnode.parent;

CNode temp=(CNode)malloc(sizeof(CNode));
temp->child=ptnode.data;
temp->next=NULL;

if(ptnode.parent>=0)
{
if(NULL == tree.node[ptnode.parent].firstchild) //尚未接孩子
{
tree.node[ptnode.parent].firstchild = temp;
}
else
{
CNode pre=tree.node[ptnode.parent].firstchild;
while(NULL != pre->next)
pre=pre->next;
pre->next=temp;
}
}
}

//输出树
void print_ctree(CTree &tree)
{
int i;
for(i=0;i<=tree.count;i++)
{
cout<<" "<<i<<" "<<tree.node[i].data<<" "<<tree.node[i].parent<<" ";
CNode temp=tree.node[i].firstchild;
while(temp!=NULL)
{
cout<<temp->child<<" ";
temp=temp->next;
}
cout<<endl;
}
}

int main()
{
FILE *fin=fopen("树的表示法.txt","r");

CTree ctree;
init_ptree(ctree);
PTNode ptnode;

while(fscanf(fin,"%c%d",&ptnode.data,&ptnode.parent)!=EOF)
{
add_ptnode(ctree,ptnode);
fscanf(fin,"%c%d",&ptnode.data,&ptnode.parent);
}
//输出树
cout<<"数组下标 节点值 双亲位置 子节点"<<endl;
print_ctree(ctree);

fclose(fin);
return 0;
}