二叉树

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstring>
#include <malloc.h>

using namespace std;
typedef struct node {
    char data;
    struct node *lchild;
    struct node *rchild;
}btnode;

typedef struct btree {
    struct node *root;
}btree;

btnode *newnode() {
    btnode *p = (btnode*)malloc(sizeof(btnode));
    return p;
}

void creat(btree *bt) {
    bt->root = NULL;
}

void make(btree *bt, char x, btree* lt, btree* rt) {
    btnode *p = newnode();
    p->data= x;
    p->lchild = lt->root;
    p->rchild = rt->root;
    bt->root = p;
}

void pre_order(btnode *t) {
    if(t) {
        printf("%c", t->data);
        pre_order(t->lchild);
        pre_order(t->rchild);
    }
}

void in_order(btnode *t) {
    if(t) {
        in_order(t->lchild);
        printf("%c", t->data);
        in_order(t->rchild);
    }
}

void post_order(btnode *t) {
    if(t) {
        post_order(t->lchild);
        post_order(t->rchild);
        printf("%c", t->data);
    }
}

int heigh(btnode *t) {
    int lh = 0, rh = 0;
    if(!t) {
        return 0;
    }
    else{
        lh = heigh(t->lchild);
        rh = heigh(t->rchild);
        if(lh>rh) {
            return lh+1;
        }
        else {
            return rh+1;
        }
    }
}

int leaf(btnode *t) {
    int counter = 0;
    if(!t) {
        return 0;
    }
    else if(t->lchild == NULL && t->rchild == NULL) {
        return 1;
    }
    else {
      return  counter = leaf(t->lchild) + leaf(t->rchild);
    }
}

int main()
{
    btree a, x, y, z;
    int temp;
    int sum;
    creat(&a);
    creat(&x);
    creat(&y);
    creat(&z);
    make(&y, 'E', &a, &a);
    make(&z, 'F', &a, &a);
    make(&x, 'C', &y, &z);
    make(&y, 'D', &a, &a);
    make(&z, 'B', &y, &x);
    pre_order(z.root);
    cout << endl;
    in_order(z.root);
    cout << endl;
    post_order(z.root);
    cout << endl;
    printf("The height of the tree:\n");
    temp = heigh(z.root);
    cout << temp << endl;
    printf("The amount of the leaf:\n");
    sum = leaf(z.root);
    cout << sum << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值