上个周的数据结构作业,孩子又少了不少脑细胞
题目:
编写算法,不重复地输出以孩子兄弟链表存储的树 T 中所有的边。输出形式为 (k1,k2),…,(ki,kj),…,其中 ki 和 kj 为树结点中的标识
头文件 宏定义 使用结构
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
typedef struct CSNode
{ ElemType data;
struct CSNode* firstchild;//该结点的第一个孩子
struct CSNode* nextbro;//该结点的下一个兄弟
}CSNode,*CSTree;
树的建立
int CreateTree(CSTree* root)//种树
{ int data;
scanf("%d",&data);
if(data<=0)
{ *root=NULL;
return 0;
}
*root=(CSTree)malloc(sizeof(CSNode));
if(!root){
printf("failed\n");
}
if(data>0){
(*root)->data=data;
CreateTree(&((*root)->firstchild));
CreateTree(&((*root)->nextbro));
}
return 0;
}
方法和二叉链表树是完全一样的,只不过把左右节点换成firstchild和nextbro
边输出函数
void PutOut(CSTree root)
{ if(root->firstchild==NULL)
return;
CSTree p=root->firstchild;
while(p!=NULL)
{ printf("(%d,%d)\n",root->data,p->data);
PutOut(p);
p=p->nextbro;
}
}
因为要不重复的输出边,所以遍历方法就是从上到下遍历,一直递归到这个结点不存在孩子,总的来说还是很简单的
结果测试
主函数:
int main()
{ CSTree root;
CreateTree(&root);
PutOut(root);
}
输入及输出