1. 程式人生 > >二叉樹基本運算

二叉樹基本運算

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
char data;
struct node* lchild,*rchild;

}BSTree;
void initiate(BSTree** bt)
{
*bt=NULL;
}

void creatBSTree(BSTree**T)
{
char n;
printf(“input a data\n”);
scanf("%c",&n);
getchar();
if(n==‘0’)
*T=NULL;
else
{
T=(BSTree

)malloc(sizeof(BSTree));
(*T)->data=n;
(*T)->lchild=NULL;
(*T)->rchild=NULL;
creatBSTree(&(*T)->lchild);
creatBSTree(&(*T)->rchild);
}
}
void showBST(BSTree *t)
{
if(t==NULL)
return;
else
{
printf("%c",t->data);
showBST(t->lchild);
showBST(t->rchild);
}

}
int calBSTdeep(BSTree* t)
{
int ldeep=0,rdeep=0;
if(t==NULL)
return 0;
else
{
ldeep = calBSTdeep(t->lchild);
rdeep = calBSTdeep(t->rchild);
if(ldeep>rdeep)
return ldeep+1;
else
return rdeep+1;
}
}

int BSTleafnode(BSTree* t)
{
int n1=0,n2=0;
if(tNULL)
return 0;
if((t->lchild
NULL)&&(t->rchild==NULL))
return 1;
else
{

n1+=BSTleafnode(t->lchild);
n1+=BSTleafnode(t->rchild);
return n1+n2;

}
}

void search(BSTree* t,char n)
{
if(tNULL)
return;
else
{
if(n
t->data)
printf("\nsuccess");
return ;
search(t->lchild,n);
search(t->rchild,n);
}

}

int main()
{
BSTree* t;
initiate(&t);
creatBSTree(&t);
showBST(t);
printf("\ndeep=%d",calBSTdeep(t));
printf("\nleaf number is %d",BSTleafnode(t));
search(t,‘1’);
return 0;
}