数据结构代码集锦3

roseying 2019-12-08

#include<stdio.h>
#include<math.h>

int Bdepth(BiTree b)
{ //求二叉树的高度
    int ldepth,rdepth;
    if(b==NULL)
        return 0;
    ldepth = Bdepth(b->lchild);
    rdepth = Bdepth(b->rchild);
    return (ldepth>rdepth)?(ldepth+1):(rdepth+1);
}
int Bignodes(BiTree b,Elemtype x)
{//求二叉树b中所有大于x结点的值的个数
    int num1,num2,num=0;
    if(b==NULL)
        return 0;
    num1 = Bignodes(b->lchild,x);
    num2 = Bignodes(p->rchild,x);
    num += num1+num2;
    if(b->data>x) //if(b->data<x)变成求小于x结点值的个数
        num++;
    return num;
}

/*统计二叉树中第k层结点的个数
思想:采用先序遍历的递归算法,num初值为0,若当前访问结点b是第k层上的叶子节点
则num++,再求出左右子树第k层上的叶子节点个数num1,num2,最后返回num1+num2*/
int Lnodes(BiTree b,int h,int k,int n) 
{ 
 //h是b所在的层数,初值为1,n是第k层结点的个数,初值为0
    if(b==NULL)
        return 0;
    else
    {
        if(h==k)  n++;
        else if
        {
            Lnodes(b->lchild,h+1,k,n);
            Lnodes(b->rchild,h+1,k,n);
        }
    }
}
int LevelLnodes(BiTree b,int k)
{
    return Lnodes(b,1,k,0);
}

int Leafnums(BiTree b,int h,int k)
{ //求二叉树第k层上叶子结点的个数
    int num1,num2,num=0;
    if(b==NULL)
        return 0;
    else 
    {
        if(h==k&&b->lchild==NULL&&b-rchild==NULL)
            num++;
        num1 = Leafnums(b->lchild,h+1,k,n);
        num2 = Leafnums(b->lchild,h+1,k,n);
        num += num1+num2;
        return num;
    }
}
int LevelLeafk(BiTree b,int k) //求b中第k层上的叶子结点的个数
{
    return Leafnums(b,1,k);
}
void FindMinNode(BiTree b,char min)
{ //求二叉树最小值的结点值
    if(b->data<x)
        min = b->data;
    FindMinNode(b->lchild,min); //在左子树中找最小值结点值
    FindMinNode(b->rchild,min);  //在右子树中找最小值结点值
}
void MinNode(BiTree b) //输出最小结点值
{
    if(b!=NULL)
    {
        char min = b->data;
        FindMinNode(b,min);
        printf("Min = %c",min);
    }
}

void FindMaxNode(BiTree b,char Max)
{ //求二叉树中最大值的结点
    if(b->data>Max)
        Max = b->data;
    FindMaxNode(b->lchild,Max);
    FindMaxNode(b->rchild,Max);
}
void MaxNode(BiTree b)
{
    char max = b->data;
    FindMaxNode(b,max);
    printf("Max = %c\n",max);
}

相关推荐