#include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h> typedef int ElemType; typedef struct CSNode//孩子兄弟表示法类型定义 { ElemType data; struct CSNode *firstchild,*nextsibling;//指向第一个孩子和下一个兄弟 }CSNode,*CSTree; void InitCSTree(CSTree *T);//树的初始化 void DestroyCSTree(CSTree *T);//树的摧毁操作 void CreateCSTree(CSTree *T,ElemType *e,int *index);//创建树操作 int DepCSTree(CSTree T);//求树的深度 void PreTraverseCSTree(CSTree T,void(*visit)(ElemType *e));//树的先根遍历 void PostTraverseCSTree(CSTree T,void(*visit)(ElemType *e));//树的后根遍历 void DisplayCSTree(ElemType *e);//输出树的结点 #include "Tree.h" void InitCSTree(CSTree *T)//树的初始化 { *T = 0; } void DestroyCSTree(CSTree *T)//树的摧毁操作 { CSTree p = *T; if(p) { DestroyCSTree(&(p->firstchild)); DestroyCSTree(&(p->nextsibling)); free(p); *T = 0; } } void CreateCSTree(CSTree *T,ElemType *e,int *index)//创建树操作 { if(e[*index] == 0) { *T = 0; (*index)++; } else { *T = (CSTree)malloc(sizeof(CSNode)); (*T)->data = e[*index]; (*index)++; CreateCSTree(&((*T)->firstchild),e,index); CreateCSTree(&((*T)->nextsibling ),e,index); return; } } int DepCSTree(CSTree T)//求树的深度 { CSTree p; int k,d = 0; if(T == NULL) { return 0; } p = T->firstchild ; while(p != NULL) { k = DepCSTree(p); if(d < k) { d = k; } p = p->nextsibling ; } return d+1; } void PreTraverseCSTree(CSTree T,void(*visit)(ElemType *e))//树的先根遍历 { if(T) { (*visit)(&T->data); PreTraverseCSTree(T->firstchild ,visit); PreTraverseCSTree(T->nextsibling ,visit); } } void PostTraverseCSTree(CSTree T,void(*visit)(ElemType *e))//树的后根遍历 { if(T) { PostTraverseCSTree(T->firstchild ,visit); (*visit)(&T->data); PostTraverseCSTree(T->nextsibling ,visit); } } void DisplayCSTree(ElemType *e)//输出树的结点 { printf("%2c",*e); } #include "Tree.h" int main(void) { int text[] = {'A','B','E',0,'F','H',0,'I',0,'J',0,0,0,'C',0,'D','G',0,0,0,0}; int h = 0; CSTree T; InitCSTree(&T); CreateCSTree(&T,text,&h); printf("树的先根遍历结果是:\n"); PreTraverseCSTree(T,DisplayCSTree); printf("\n"); printf("树的后根遍历结果是:\n"); PostTraverseCSTree(T,DisplayCSTree); printf("\n"); printf("树的深度是:%2d",DepCSTree(T)); printf("\n"); DestroyCSTree(&T); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/weichanjuan3/article/details/47110801