#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define NULL 0
typedef struct node
{
int data;
struct node * lchild;
struct node * rchild;
}Btree;
Btree*CreateBtree(int a[], int n)
{
int i;
Btree*root, *pb, *pa, *pc;
root = (Btree*)malloc(sizeof(Btree));
root->data = a[0];
root->lchild = root->rchild = NULL;
for (i = 1; i < n; i++)
{
pb = (Btree*)malloc(sizeof(Btree));
pb->data = a[i];
pb->lchild = pb->rchild = NULL;
pc = root;
while (pc)
{
pa = pc;
if (pc->data > pb->data) pc = pc->lchild;
else pc = pc->rchild;
}
if (pa->data > pb->data)
pa->lchild = pb;
else pa->rchild = pb;
}
return root;
}
void PreOrder(Btree*root)
{
if(root)
{
printf("%5d",root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void InOrder(Btree*root)
{
if(root)
{
InOrder(root->lchild);
printf("%5d",root->data);
InOrder(root->rchild);
}
}
void PostOrder(Btree*root)
{
if(root)
{
PostOrder(root->lchild);
PostOrder(root->rchild);
printf("%5d",root->data);
}
}
int CountNode(Btree*root)
{
int cr,cl;
if(root)
{
cr=CountNode(root->rchild);
cl=CountNode(root->lchild);
}
return cr+cl+1;
}
int DepthTree(Btree*root)
{
int dr,dl,d=0;
if(root)
{
dr=DepthTree(root->rchild);
dl=DepthTree(root->lchild);
d=dl>dr?dl+1:dr+1;
}
return d;
}
void main()
{
Btree*root = NULL;
int a[] = { 5,3,1,7,6,4,8,2 },count=0,d=0;
root = CreateBtree(a, 8);
PreOrder(root);
InOrder(root);
PostOrder(root);
count=CountNode(root);
printf("%5d",count);
d=DepthTree(root);
printf("%5d",d);
getchar();
}
#include<malloc.h>
#include<stdlib.h>
#define NULL 0
typedef struct node
{
int data;
struct node * lchild;
struct node * rchild;
}Btree;
Btree*CreateBtree(int a[], int n)
{
int i;
Btree*root, *pb, *pa, *pc;
root = (Btree*)malloc(sizeof(Btree));
root->data = a[0];
root->lchild = root->rchild = NULL;
for (i = 1; i < n; i++)
{
pb = (Btree*)malloc(sizeof(Btree));
pb->data = a[i];
pb->lchild = pb->rchild = NULL;
pc = root;
while (pc)
{
pa = pc;
if (pc->data > pb->data) pc = pc->lchild;
else pc = pc->rchild;
}
if (pa->data > pb->data)
pa->lchild = pb;
else pa->rchild = pb;
}
return root;
}
void PreOrder(Btree*root)
{
if(root)
{
printf("%5d",root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void InOrder(Btree*root)
{
if(root)
{
InOrder(root->lchild);
printf("%5d",root->data);
InOrder(root->rchild);
}
}
void PostOrder(Btree*root)
{
if(root)
{
PostOrder(root->lchild);
PostOrder(root->rchild);
printf("%5d",root->data);
}
}
int CountNode(Btree*root)
{
int cr,cl;
if(root)
{
cr=CountNode(root->rchild);
cl=CountNode(root->lchild);
}
return cr+cl+1;
}
int DepthTree(Btree*root)
{
int dr,dl,d=0;
if(root)
{
dr=DepthTree(root->rchild);
dl=DepthTree(root->lchild);
d=dl>dr?dl+1:dr+1;
}
return d;
}
void main()
{
Btree*root = NULL;
int a[] = { 5,3,1,7,6,4,8,2 },count=0,d=0;
root = CreateBtree(a, 8);
PreOrder(root);
InOrder(root);
PostOrder(root);
count=CountNode(root);
printf("%5d",count);
d=DepthTree(root);
printf("%5d",d);
getchar();
}