数据结构 c语言版 树和森林 孩子兄弟链表表示 不重复输出每条边

上个周的数据结构作业,孩子又少了不少脑细胞

题目:
编写算法,不重复地输出以孩子兄弟链表存储的树 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;
}

方法和二叉链表树是完全一样的,只不过把左右节点换成firstchildnextbro

边输出函数

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

输入及输出
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值