广工anyview数据结构第7~8章

第七章

/**********
【题目】试编写算法,对一棵以孩子兄弟链表表示
的树统计叶子的个数。
孩子兄弟链表类型定义:
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
  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值