数据结构_树的深度
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
建立树的存储结构
求树的深度
*/
1.源程序:
#include
#include
#define MAX 100
typedef struct CSNode{ //树
char data;
struct CSNode *firstchild, *nextsibling;
}CSNode;
typedef struct {
CSNode* *elem;
int front;
int rear;
}LinkQueue;
void InitQueue(LinkQueue &Q){
Q.elem=(CSNode **)malloc(MAX*sizeof(CSNode));
Q.front=Q.rear=0;
}
CSNode* EnQueue(LinkQueue &Q,CSNode *p)
{
if(Q.front==Q.rear) Q.elem[Q.front]=p;
Q.rear++;
Q.elem[Q.rear]=p;
return p;
}
CSNode* DeQueue(LinkQueue &Q,CSNode *p)
{
p=Q.elem[Q.front];
Q.front++;
return p;
}
CSNode* GetHead(LinkQueue Q,CSNode *p){
if(Q.rear != Q.front) p=(Q.elem[Q.front]);
else p=NULL;
return p;
int TreeDepth(CSNode *T) {
if(!T) return 0;
else {
int h1 = TreeDepth( T->firstchild );
int h2 = TreeDepth( T->nextsibling);
return( (h1+1>h2)? h1+1: h2);
}
}
CSNode* GetTreeNode(char c){
CSNode *C;
C=(CSNode *)malloc(sizeof(CSNode));
C->data=c;
C->firstchild=NULL;
C->nextsibling=NULL;
return C;
}
void Preorder(CSNode *T) //先序遍历
{
if (T){
printf("%c\t",T->data); // 访问结点
Preorder(T->firstchild); // 遍历左子树
Preorder(T->nextsibling); // 遍历右子树
}
}
CSNode * CreatTree( CSNode *T ) {
char ch,fa;
LinkQueue Q;
InitQueue(Q);
CSNode *p,*r,*s;
p=(CSNode *)malloc(sizeof(CSNode));
r=(CSNode *)malloc(sizeof(CSNode));
s=(CSNode *)malloc(sizeof(CSNode));
printf("请输入树的序列:\n");
scanf("%c %c",&fa,&ch);
while( ch!='0'){
p = GetTreeNode(ch); // 创建结点
p=EnQueue(Q, p); // 指针入队列
if (fa == '#') T = p; // 所建为根结点
else {
s=GetHead(Q,s); // 取队列头元素(指针值)
while (s->data != fa ) { // 查询双亲结点
s=DeQueue(Q,s);
s=GetHead(Q,s);
}
if (!(s->firstchild)) {
s->firstchild = p;
r = p;
} // 链接第一个孩子结点
else {
r->nextsibling = p;
r = p;
} // 链接其它孩子结点
}
getchar();
scanf("%c %c",&fa,&ch);
}
Preorder(T);
printf("\n");
return T;
}
void main()
{
CSNode *T;
T=(CSNode *)malloc(MAX*sizeof(CSNode));
T=CreatTree(T);
int depth;
depth=TreeDepth(T);
printf("该树的深度为:%d\n",depth);
}
2.运行窗口截图: