计算二叉树的高度和结点数

#include <cstdio>

typedef char TElemType;

typedef struct node {
    TElemType data;
    struct node *left_child;
    struct node *right_child;
} BTNode, *BinTree;

int node_count = 0;
int leaf_count = 0;
int one_count = 0;
int flag = 0;

void Create( BTNode*& t) {
    char c;
    char ch;
    scanf( "%c", &c );
    ch = getchar();
    if( c =='#' )
        t = NULL;
    else {
        t = new BTNode;
        t->data = c;
        Create( t->left_child );
        Create( t->right_child );
    }
}

void PreOrder( BTNode* t ) {
    if( t != NULL ) {
        printf( " %c", t->data );
        PreOrder( t->left_child );
        PreOrder( t->right_child );
    }
}

void InOrder( BTNode *t ) {
    if( t != NULL ) {
        InOrder( t->left_child );
        printf( " %c", t->data );
        InOrder( t->right_child );
    }
}

void PostOrder( BTNode *t ) {
    if( t != NULL ) {
        PostOrder( t->left_child );
        PostOrder( t->right_child );
        printf( " %c", t->data );
    }
}

int Height( BTNode *t ) {
    int i, j;
    if( t == NULL ) return 0;
    else {
         i = Height( t->left_child );
         j = Height( t->right_child );
    }
    return ( i > j ) ? ( i + 1 ) : ( j + 1 );
}

void BTNode_Count( BTNode *t ) {
    if( t == NULL ) return ;
    else {
         BTNode_Count( t->left_child );
         BTNode_Count( t->right_child );
         node_count++;
    }
}

void BTNode_LeafCount( BTNode *t ) {
    if( t == NULL ) return ;
    else {
        if( t->left_child == NULL && t->right_child == NULL ) {
            leaf_count++;
            //cout << T->data << endl;
        }
        else if( t->left_child == NULL && t->right_child != NULL || t->left_child != NULL && t->right_child == NULL ){
            one_count++;
        }
        BTNode_LeafCount( t->left_child );
        BTNode_LeafCount( t->right_child );
    }
}
int main() {
    BTNode T;
    BinTree root = &T;
    Create( root );
    printf( "PreOrder:" );
    PreOrder( root );
    printf( "\n" );
    printf( "InOrder:" );
    InOrder( root );
    printf( "\n" );
    printf( "PostOrder:" );
    PostOrder( root );
    int height = Height( root );
    BTNode_Count( root );
    BTNode_LeafCount( root );
    printf( "\n%d\n%d %d %d", height, node_count, leaf_count, one_count );
    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值