二叉树的基本操作

计算二叉树的叶子节点写法一:

int countLeaf(BiNode *root)
{
    int count=0;
    if(root)
    {
        if(root->lChild==NULL && root->rchild==NULL)
        {
            count++;
        }
        if(root->lChild)
        {
            countLeaf(root->lChild);
        }
        if(root->rChild)
        {
            countLeaf(root->rChild);
        }
    }
    return count;
}

 

copy一棵二叉树

BiNode *CopyTree(BiNode *T)
{
    BiNode *newLptr=NULL.*newRptr=NULL;
    BiNode *newNode=NULL;
    if(T->lchile!=NULL)
    {
        newLptr=CopyTree(T->lchild);
    }
    else
    {
        newLptr=NULL;
    }
    if(T->Rchile!=NULL)
    {
        newRptr=CopyTree(T->Rchild);
    }
    else
    {
        newRptr=NULL;
    }
    newNode=(BiNode *)malloc(sizeof(BiNode));
    if(newNode==NULL)
    {
        return NULL;
    }
    newNode->lchild=newLptr;
    newNode->Rchild=newRptr;
    newNode->data=T->data;
    return newNode;
}

求叶子节点数目

void countLeafNum(BiNode *root,int *num)
{
    if(root!=NULL)
    {
        countLeafNum(root->lchild);//递归遍历左子树
        if(root->lchild==NULL&&root->rchild==NULL)
        {
            (*num)++;
        }
        countLeafNum(root->rchild);//递归遍历右子树
    }    
}

 求二叉树的深度

int GetTreeDeapth(BiNode *root)
{
    int deapth=0,ldeapth=0,rdeapth=0;
    if(r00t=NULL)
    {
        deapth=0;
        return deapth
    }
    ldeapth=GetTreeDeapth(root->lchild);
    rdeapth=GetTreeDeapth(root->rchild);
    deapth=1+((ldeapth>rdeapth)?ldeapth:rdeapth);
    return deapth;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值