【数据结构】二叉树队列求树高 自用

#include<stdio.h>
#include<stdlib.h>

typedef struct BiNode{
    int data;
    struct BiNode *lchild, *rchild;
}BiNode, *BiTree;

// 初始化
void InitBiNode(BiNode *T){
    T->lchild=NULL;
    T->rchild=NULL;
};

// 求树高
int Height(BiTree T){
    if(!T)
        return 0;
    // front队头,rear队尾,last当前层最右结点,level层数
    int front=-1, rear=0, last=0, level=0;
    BiTree Q[10];
    BiTree p;
    Q[rear]=T;
    while(front<rear){
        p=Q[++front];
        // printf("当前指向%d",p->data);
        if(p->lchild)
            Q[++rear]=p->lchild;
        if(p->rchild)
            Q[++rear]=p->rchild;
        if(front==last){
            level++;
            // printf(" 当前层高为%d\n",level);
            last=rear;
        }
    }
    return level;
};

int main(){
    // 造个树
    BiNode *p,*q,*r,*s;
    p=(BiNode *)malloc(sizeof(BiNode));
    q=(BiNode *)malloc(sizeof(BiNode));
    r=(BiNode *)malloc(sizeof(BiNode));
    s=(BiNode *)malloc(sizeof(BiNode));
    InitBiNode(p);
    InitBiNode(q);
    InitBiNode(r);
    InitBiNode(s);
    p->lchild=q;
    q->data=2;
    p->rchild=r;
    r->data=3;
    r->rchild=s;
    s->data=4;
    // 运行函数
    printf("总层高为%d",Height(p));
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值