创建孩子兄弟链表的树c语言,一般树的建立(孩子兄弟链表) 、遍历、深度

#include

#include

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值