树的存储结构
双亲表示法
#include "stdio.h"
#include "stdlib.h"
#define ElemType int
#define MAX_SIZE 100
typedef struct {
ElemType data;
int parent;
}PTNode;
typedef struct {
PTNode nodes[MAX_SIZE];
int n;
}PTree;
孩子表示法
#include "stdio.h"
#include "stdlib.h"
#define ElemType int
#define MAX_SIZE 100
struct KTNode{
int child;
struct KTNode *next;
};
typedef struct {
ElemType data;
struct KTNode *firstChild;
}KTBox;
typedef struct {
KTBox nodes[MAX_SIZE];
int n,r;
}KTree;
孩子兄弟表示法
#include "stdio.h"
#include "stdlib.h"
#define ElemType int
typedef struct CSNode{
ElemType data;
struct CSNode *firstchild,*nextsibling;
}CSNode,*CSTree;
![在这里插入图片描述](https://img-blog.csdnimg.cn/0495f047ce9b4222bdf07cb84fd4ccd9.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTM5MzgyMg==,size_16,color_FFFFFF,t_70#pic_center)
int Leaves(CSTree T){
if(T==NULL)
return 0;
if(T->firstchild==NULL)
return 1+ Leaves(T->nextsibling);
else
return Leaves(T->firstchild)+ Leaves(T->nextsibling);
}
int Height(CSTree T){
int hc,hs;
if(T==NULL)
return 0;
else{
hc= Height(T->firstchild);
hs= Height(T->nextsibling);
if(hc+1>hs)
return hc+1;
else
return hs;
}
}
void CreateCSTree(CSTree &T,ElemType e[],int degree[],int n){
CSNode *pointer=new CSNode[15];
int i,j,d,k=0;
for(i=0;i<n;i++){
pointer[i].data=e[i];
pointer[i].firstchild=pointer[i].nextsibling=NULL;
}
for(i=0;i<n;i++){
d=degree[i];
if(d){
k++;
pointer[i].firstchild=pointer[k];
for(j=2;j<=d;j++){
k++;
pointer[k-1].nextsibling=pointer[k];
}
}
}
T=pointer[0];
}