一般树的建立(孩子兄弟链表) 、遍历、深度

本文介绍了一种使用孩子-兄弟链表表示的树结构,并提供了创建这种树的算法及通过先序遍历输出从根到叶子路径的方法。文章还展示了如何计算树的深度和节点数量。

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

#include<stdio.h>
#include<stdlib.h>

typedef struct csnode
{
int data;
int in;
struct csnode *lchild;
struct csnode *nextsibling;
}CSNode;
CSNode *t,*q;

int preoder()//通过先序遍历的方式输出该树一条从根到叶子的路径
{ //顺便求树的深度
CSNode *stact[1001],*p;
int i,high=-1;
int top=-1;
p=t;
while(p||top!=-1)
{
while(p)
{
top++;
stact[top]=p;
p=p->lchild;

}
if((stact[top]->in)==0)
{
for(i=0;i<=top;i++)
printf("%d ",stact[i]->data);
if(top>high)
high=top;
printf("\n");
}
if(top<0)
break;
else
{
p=stact[top];
top--;
p=p->nextsibling;

}
}
return high;
}

// 创建“孩子-兄弟链表”方式存储的树
int CreatTree( int n)
{

int k,i,j,h; // 父节点编号,子节点编号
t = NULL;
CSNode *queue[1001],*p;
int head,tail;
head=0;
tail=-1;
for(k=1; k<=n;k++)
{
scanf("%d%d",&i,&j);
p=(CSNode*)malloc(sizeof(CSNode)); // 创建结点
p->lchild=NULL;
p->nextsibling=NULL;
p->data=j;
(p->in)=0;
tail++;
queue[tail]=p; //最终 tail+1 为树的总结点的数目

if(i==-1)// 所建为根结点
t=p;//
else // 非根结点的情况
{
for(h=head;h<=tail;h++) //当然这里可以添加条件

//防止 相同的节点的再次出现
if(queue[h]->data==i)
{
queue[h]->in++;
break;
}
q=queue[h];

if (!(q->lchild) ) // 链接第一个孩子结点

q->lchild = p;
// r = p;

else // 链接其它孩子结点
{
q=q->lchild;
while(q->nextsibling)
q=q->nextsibling;
q->nextsibling = p;

}
}
} // for
return tail;
} // CreateTree


int main()
{ //freopen("1.txt","r",stdin);
int high, n;;
scanf("%d",&n);
printf("树一条从根到叶子的路径:\n");
n=CreatTree(n);
high= preoder();
printf("树的深度:%d 树的节点数:%d\n",high+1,n+1);
return 0;
}

/*

n=7

i=fa j
-1 1
1 2
1 3
1 4
3 5
3 6
5 7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值