5.6 数据结构——二叉树的建立

5.6.1二叉树的建立

本文按先序遍历序列的方式建立二叉树的二叉链表。

(1)从键盘输入二叉树的结点信息,建立二叉树的存储结构。

(2)在建立二叉树的过程中按照二叉树的先序方式建立

对上图所示二叉树,按下列顺序读入字符:

ABC##DE#G##F### 

void CreateBiTree(BiTree *T)
{
    ElemType ch;
    scanf("%c", &ch);
    if (ch == "#")
        *T = NULL;
    else
    {
        *T = (BiTree)malloc(sizeof(BiTNode));
        if (!*T)
            exit(OVERFLOW);
        (*T)->data = ch;
        CreateBiTree(&(*T)->lchild);   //构建左子树
        CreateBiTree(&(*T)->rchild);   //构建右子树
    }

}

5.6.2 复制二叉树

如果是空树,递归结束,否则申请新结点空间,复制根结点,递归复制左子树,递归复制右子树。

int Copy(BiTree T, BiTree *newT)
{
    if (T == NULL)
        return 0;
    else
    {
        *newT = (BiTree)malloc(sizeof(BiTNode));
        *newT->data = T->data;
        copy(T->lchild, &(*newT)->lchild);     //复制左子树
        copy(T->lchild, &(*newT)->lchild);     //复制右子树
    }
    return 1;
}

5.6.3 计算二叉树的深度

如果是空树,则深度为0,否则递归计算左子树的深度记为m,递归计算右子树的深度记为n,二叉树的深度为m与n的较大者加1。

int Depth(BiTree T)
{
    if (T == NULL)
        return 0;
    else
    {
        m = Depth(T->lchild);
        n = Depth(T->rchild);
        if (m > n)
            return m+1;
        else
            return n+1;
    }
}

5.6.4 计算二叉树结点总数

如果是空树,则结点数为0,否则结点数为左子树的结点个数+右子树的结点个数+1。

int NodeCount(BiTree T)
{
    if (T == NULL)
        return 0;
    else
        return NodeCount(T->lchild) + NodeCount(T->rchild) + 1;
}

5.6.5 计算二叉树叶子结点个数

如果是空树,则叶子结点个数为0,否则叶子结点个数是左子树的叶子结点个数 + 右子树的叶子结点个数。

int LeafCount(BiTree T)
{
    if (T == NULL)
        return 0;

    if (T->lchild == NULL && T->rchild == NULL)
        return 1;
    else
    {
        return LeafCount(T->lchild) + LeafCount(T->rchild);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值