计算树的深度

作者在 2010-12-10 12:59:44 发布以下内容
#include <stdio.h>
#include <stdlib.h>
typedef char telemtype;
typedef struct tnode{
    telemtype data;
    struct tnode *hp,*vp;}tnode,*bitree;
int visit(bitree p){
    int max=0;
    if(p!=NULL){
        printf("%c ",p->data);
        visit(p->hp);
        visit(p->vp);
    }
    return max;
}
void createbt(bitree &bt){
    char ch;
    scanf("%c",&ch);
    if(ch=='#')bt=NULL;
    else{
        bt=(bitree)malloc(sizeof(tnode));
        bt->data=ch;
        createbt(bt->hp);
        createbt(bt->vp);
    }
}
int height(bitree &bt){
    tnode *p;
    int m,max=0;
    if(bt==NULL)
        return 0;
    else if(bt->vp==NULL)
        return 1;
    else{
        p=bt->vp;
        while(p!=NULL){
            m=height(p);
            if(max<m) max=m;
            p=p->hp;
        }
        return m+1;
    }
}
void main(){
    bitree bt;
    printf("请输入树:");
    createbt(bt);
    printf("树为:\n");
    visit(bt);
    printf("\n树深为%d\n",visit(bt));
}

程序 | 阅读 904 次
文章评论,共0条
游客请输入验证码
浏览31541次