第七章
/**********
【题目】试编写算法,对一棵以孩子兄弟链表表示
的树统计叶子的个数。
孩子兄弟链表类型定义:
typedef struct CSTNode {
TElemType data;
struct CSTNode *firstChild, *nextSibling;
} CSTNode, *CSTree;
**********/
int Leave(CSTree T) /* 统计树T的叶子数 */
{
if(!T)
return 0;
if(!T->firstChild)
return 1+Leave(T->nextSibling);
return Leave(T->firstChild)+Leave(T->nextSibling);
}
/**********
【题目】试编写算法,求一棵以孩子兄弟链表表示的树的度。
孩子兄弟链表类型定义:
typedef struct CSTNode {
TElemType data;
struct CSTNode *firstChild, *nextSibling;
} CSTNode, *CSTree;
**********/
int Degree(CSTree T) /* 求树T的度 */
{
int ds,dt,d;
CSTree p;
if(!T)
return 0;
ds=0; dt=0;
for( p = T->firstChild; p ; p= p->nextSibling){
dt++;
d= Degree(p);
if(d>ds)
ds =d;
}
return ds>dt?ds:dt;
}
/**********
【题目】试编写算法,对以双亲表示法存储的树计算深度。
typedef struct {
TElemType data;
int parent; // 双亲位置
} PTNode; // 结点类型
typedef struct {
PTNode nodes[MAX_TREE_SIZE]; // 结点存储空间
int n, r; // 结点数和根的位置
} PTree;
**********/
int PTreeDepth(PTree T) /* 求树T的深度 */
{
int maxdep = 0,i,j,dep;
for(i=0; i<T.n;i++){
dep=0;
for(j =i; j>0; j=T.nodes[j].parent)
dep++;
if(dep>maxdep)
maxdep = dep;
}
return maxdep+1;
}
/**********
【题目】试编写算法,对以双亲孩子表示法存储的树计算深度。
孩子链表类型定义:
typedef struct ChildNode { // 孩子结点
int childIndex;
struct ChildNode *nextChild;
} ChildNode; // 孩子结点类型
typedef struct {
TElemType data;
int parent; // 双亲位置
struct ChildNode *firstChild; // 孩子链表头指针
} PCTreeNode; // 结点类型
typedef struct {
PCTreeNode *nodes; // 结点存储空间
int n, r; // 结点数和根的位置
} PCTree;
**********/
int fun(PCTree T, int pos)
{
if(T.nodes[pos].firstChild == NULL)
return 1;
ChildNode *temp = T.nodes[pos].firstChild;
int depth = 1, max = 1;
while(temp != NULL) {
if( T.nodes[temp->childIndex].firstChild != NULL){
depth = fun(T, temp->childIndex);
if(depth > max)
max = depth;
}
temp = temp->nextChild;
}
return max + 1;
}
int PCTreeDepth(PCTree T) /* 求树T的深度*/
{
int depth;
depth = fun(T, T.r);
return depth;
}
/**********
【题目】试编写算法,对以孩子-兄弟链表表示的树计算深度。
孩子兄弟链表类型定义:
typedef struct CSTNode {
TElemType data;
struct CSTNode *firstChild, *nextSibling;
} CSTNode, *CSTree;
**********/
int TreeDepth(CSTree T)
/* 求树T的深度 */
{
int dep1,dep2,dep;
if(!T)
dep = 0;
else