二叉树的深度与宽度C#实现

typedef struct node{
    int data;
    node *left;
    node *right;
}Node,*Tree;

求二叉树的宽度。宽度:有结点数最多的那一层的结点个数。



void order(Tree tree,int lay, int a[]){   //二叉树,层数,辅助数组
    if(node->left!= nullptr){
        order(node->left,lay+1,a);
    }
    if(node->right!= nullptr){
        order(node->right,lay+1,a);
    }
    a[lay] = a[lay]+ 1;                    //辅助数组,标记同一层的结点数量
} 

//求二叉树的宽度
int getWidth(Tree tree,int h){             //h二叉树的高度
    int* a=(int *)malloc(sizeof(int)*h);   //初始化数组
    for(int j =0;j<h;j++){
        a[j] = 0;
    }
    order(node,0,a);                       //遍历二叉树
    int width = a[0];                      //找出数组最大的值 
    for(int i =1;i<h;i++){                 
        if(a[i]>width){
            width = a[i];
        }
    }
    return width;                          //返回宽度

}

 求二叉树测深度。

//计算二叉树的深度
int getDepth(Tree tree,int depth){
    int i=depth,j=depth;                //初始化i,j左右子树深度与当前结点深度相同
    if(tree->left != nullptr){
        i = getDepth(tree->left,depth+1);   //i左子树深度
    }
    if(tree->right != nullptr){
        j = getDepth(tree->right,depth+1);  //i左子树深度
    }
    if(i>depth|| j>depth){                 //返回三者值最大的作为已遍历子树的深度
        if(i>j){
            return i;
        }
        else{return j;};
    }
    else{
        return depth;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值