#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;
}
二叉树
最新推荐文章于 2022-07-09 13:48:50 发布