二叉树及其应用--二叉树特征值与销毁

给定二叉树的数据类型如下

typedef char Element;
struct Node
{
    Element data;
    struct Node *lchild;
    struct Node *rchild;
};
typedef struct Node BTNode;
typedef struct Node * BTree;

①二叉树输出
完成void PrintBTree(BTree root)函数,该函数输出二叉树的广义表表示。

void PrintBTree(BTree root)
{
    if(root==NULL)return;
    printf("%c",root‐>data);
    if(root‐>lchild==NULL&&root‐>rchild==NULL)
    return;
    printf("(");
    if(root‐>lchild!=NULL)
        PrintBTree(root‐>lchild);
    printf(",");
    if(root‐>rchild!=NULL)
        PrintBTree(root‐>rchild);
    printf(")");
}

②二叉树输出叶节点
完成void PrintLeaf(BTree root)函数,该函数按先序遍历的方式输出二叉树所有的叶节点。

void PrintLeaf(BTree root)
{
    if(root==NULL)return;
    if(root‐>lchild==NULL&&root‐>rchild==NULL)
        printf("%c\n",root‐>data);
    PrintLeaf(root‐>lchild);
    PrintLeaf(root‐>rchild);
}

③二叉树叶节点数
完成int GetLeafNum(BTree root);函数,该函数统计二叉树root中叶节点数目并返回该值。

int GetLeafNum(BTree root)
{
    if(root==NULL)
        return 0;
    if(root‐>lchild==NULL&&root‐>rchild==NULL)
        return 1;
    return GetLeafNum(root‐>lchild)+GetLeafNum(root‐>rchild);
}

④二叉树树深
完成int GetDepth(BTree root)函数,该函数返回二叉树root的树深。

int GetDepth(BTree root)
{
    int ldepth,rdepth;
    if(root==NULL)
        return 0;
    rdepth=GetDepth(root‐>rchild);
    ldepth=GetDepth(root‐>lchild);
    return (rdepth>ldepth?rdepth:ldepth)+1;
}

⑤二叉树节点数
完成int GetNum(BTree root)函数,该函数统计二叉树root中节点数目并返回该值。

int GetNum(BTree root)
{
    int num;
    if(root==NULL)
        return 0;
    num=1;
    if(root‐>lchild!=NULL)
        num+=GetNum(root‐>lchild);
    if(root‐>rchild!=NULL)
        num+=GetNum(root‐>rchild);
    return num;
}

⑥二叉树销毁
完成BTree Dispose(BTree root)函数,该函数销毁二叉树并返回NUL指针。

BTree Dispose(BTree root)
{
    if(root==NULL)
        return NULL;
    Dispose(root‐>lchild);
    Dispose(root‐>rchild);
    free(root);
    return NULL;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值