DSOJ Level-order sequence with degree(森林的带度数层次遍历序列)

这篇博客探讨了如何解决DSOJ中的一个问题,即如何进行带度数的层次遍历序列。内容涉及森林的数据结构和层次遍历算法的应用。

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

题目链接


#include<stdio.h>			//Level-order sequence with degree(森林的带度数层次序列存储)
#include<string.h>
#include<stdlib.h>			//算法思想:利用队列存储输入的带度数的层次遍历序列,从队首开始遍历队列,
#define MAX 100				//根据结点度数的不同进行相应的处理

int N;					//The number of trees
int LEN[MAX];

typedef struct node
{
	char info;
	int degree;
	struct node *firstchild, *nextsibling;
}BT;

BT *transform(BT *Node[],int i)		//Create the Binary Tree from the level-order sequence with degree,return the root
{
	int front = 0, rear = 0, deg;
	BT *p, *q;
	Node[rear++]->nextsibling = NULL;
	while (rear < LEN[i])
	{
		p = Node[front++];
		deg = p->degree;
		if (deg == 0)
		{
			p->firstchild = NULL;		//叶子结点,将左指向NULL
		}
		else
		{								//非终端结点
			deg--;
			q = Node[rear++];
			p->firstchild = q;			//先向左,再向右
			while (deg--)
			{
				q->nextsibling = Node[rear++];		//兄弟结点
				q = q->nextsibling;
			}
			q->nextsibling = NULL;		//最右的兄弟结点的右指向NULL
		}
	}
	while (front < rear)			//将front之后的叶子结点的左指向NULL
	{
		Node[front]->firstchild = NULL;
		front++;
	}
	return Node[0];				//返回转化后的二叉树的根结点(此时根的右为空)
}

void inorder(BT *T)		//Inorder Traverse
{
	if (!T) return;
	inorder(T->firstchild);
	printf("%c ", T->info);
	inorder(T->nextsibling);
}


int main()
{
	int i, j;
	BT *Node[MAX];
	BT *Root[MAX];
	char c;
	scanf("%d", &N);
	c = getchar();					//Storage Enter(!!!必须要有,否则出错)
	for (i = 0; i < N; i++)
	{
		j = 0;
		do
		{
			Node[j] = (BT *)malloc(sizeof(BT));
			c = getchar();			//Storage the info
			Node[j]->info = c;
			c = getchar();			//Storage the blank
			scanf("%d", &Node[j]->degree);
			j++;
			c = getchar();			//Storage the blank or Enter,when Enter,stop
		}while (c == ' ');
		LEN[i] = j;					//Storage the number of node of each tree
		Root[i] = transform(Node, i);
	}
	for (i = 0; i < N - 1; i++)
		Root[i]->nextsibling = Root[i + 1];		//将N棵树的根节点链接起来
	inorder(Root[0]);							//Root[0]即为转换后二叉树的根节点
	printf("\n");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值