一般树的建立(孩子兄弟链表) 、遍历、深度
来源:互联网 发布:淘宝满400减50怎么用 编辑:程序博客网 时间:2024/05/16 11:03
#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
*/
- 一般树的建立(孩子兄弟链表) 、遍历、深度
- 一般树的建立(孩子兄弟链表) 、遍历、深度
- 树的左孩子 右兄弟表示法的建立过程 (后序遍历)
- 求兄弟孩子树的深度
- 树的孩子兄弟链表实现
- 树的孩子兄弟链表应用
- 左孩子右兄弟树的递归与非递归、深度与广度遍历
- 层次遍历方法建树,用队。实现树与孩子兄弟二叉链表的转化!
- 一般的树的创建,兄弟孩子表示法
- 树的孩子兄弟表示法 及遍历实现
- 求 以孩子-兄弟链表表示的树 的度、深度、叶结点和边
- /*深度优先建立深林,孩子兄弟法*/
- 孩子兄弟法 建立树和森林
- 树的存储结构(树的二叉链表(孩子—兄弟))
- 【数据结构】以孩子兄弟链表作存储结构,创建一棵树。并输出其先根、后根遍历序列;统计树中叶子结点的个数和深度
- 树、森林与二叉树(树的存储结构(树的孩子兄弟链表应用举例),树转换为二叉树,二叉树转换成树和森林,树和森林的遍历)
- 【数据结构笔记】2:基于树去建立森林的孩子-兄弟结构
- 数据结构以孩子兄弟链存储的树的高度
- NSMutableArray的正确使用
- 期待中的旅行
- POJ2391 Ombrophobic Bovines 二分+最大流dinic
- 调用initWithNibName方法时不能写上.xib
- 大家欢迎我吧
- 一般树的建立(孩子兄弟链表) 、遍历、深度
- java设计模式----工厂模式
- json
- LINQto JSON
- NSMutableArray中的自动释放对象让我郁闷了一整天
- alsa ubuntu声卡驱动重新安装
- CopyOnWriteArrayList
- 动态库使用示例代码
- xml容易出现的异常