层次遍历求树高

#include <stdio.h>
#include <stdlib.h>
#define MaxSize 50


typedef struct BiTNode{
    char data;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

BiTree CreateBiTree( ){
    char ch;
    scanf("%c",&ch);
    if(ch=='#') return NULL;
    else{
        BiTree T = (BiTree)malloc(sizeof(BiTNode));
        T -> lchild  = T -> rchild = NULL;
        T->data = ch;
        T->lchild = CreateBiTree();
        T->rchild = CreateBiTree();
        return T;
    }
}

void Depth(BiTree T){
    int front = -1 , rear = -1;
    int last = 0 , level = 0 ; 
    BiTree Q[MaxSize];
    Q[++rear] = T ;
    BiTree p;
    while( front<rear ){
        p = Q[++front];
        if(p->lchild)
            Q[++rear] = p->lchild;
        if(p->rchild)
            Q[++rear] = p->rchild;
        if(last==front){        //队头指针front移动到last时表示当前层结束
            level++;
            last = rear;        //last指向当前层的尾结点
        }
    }
    printf("%d",level);
}

int main()
{
    printf("输入各节点:\n");
    BiTree T= CreateBiTree();
    printf("树高为:\n");
    Depth(T);
}

猜你喜欢

转载自blog.csdn.net/RRWJ__/article/details/83387926