Google

笔记分类

2008年11月4日星期二

c二叉树

#include
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
typedef struct tree treenode;
typedef treenode *b_tree;

b_tree creat()
{
char ch;
b_tree newnode;
ch=getchar();
if (ch==' ') return(NULL);
else
{ newnode=(b_tree)malloc(sizeof(treenode));
newnode->data=ch;
newnode->left=creat(newnode);
newnode->right=creat(newnode);
}
return newnode;
}

void front_print(b_tree root)
{
if(root!=NULL)
{
printf("[%c]",root->data);
front_print(root->left);
front_print(root->right);
}
}

void middle_print(b_tree root)
{
if(root!=NULL)
{
middle_print(root->left);
printf("[%c]",root->data);
middle_print(root->right);
}
}

void back_print(b_tree root)
{
if(root!=NULL)
{
back_print(root->left);
back_print(root->right);
printf("[%c]",root->data);
}
}

int countleaf(b_tree root,int *i)
{
if(root==NULL)
return 0;
else
{
if((root->left==NULL)&&(root->right==NULL))
(*i)++;
countleaf(root->left,i);
countleaf(root->right,i);
return *i;
}
}

int locate(b_tree root,char x)
{
if(root==NULL)
return 0;
else
{
if(root->data==x)
printf("\nSuccess!You research data is %c",x);
locate(root->left,x);
locate(root->right,x);
}
}

int t_depth(b_tree root)
{
int dep1,dep2;
if(root==NULL)
return 0;
else
{
dep1=t_depth(root->left);
dep2=t_depth(root->right);
if(dep1>dep2)
return(dep1+1);
else
return(dep2+1);
}
}

void main()
{
b_tree root=NULL;
char x;
int select;
int depth=0;
int *i=0;
int j;
printf("Please set up a tree.\n");
printf("Notice:if no have crunode please input blank!!!\n");
root=creat();
do
{
printf("\n(1) Show the tree in a front-root order.");
printf("\n(2) Show the tree in a middle-root order.");
printf("\n(3) Show the tree in a back-root order.");
printf("\n(4) Show the the leafage number of tree.");
printf("\n(5) Locate a data in the tree.");
printf("\n(6) Show the depth of the tree.");
printf("\n(7) Exit");
printf("\nPlease select one:");
scanf("%d",&select);
switch(select)
{
case 1: printf("\nThe tree is :");
front_print(root);
break;
case 2: printf("\nThe tree is :");
middle_print(root);
break;
case 3: printf("\nThe tree is :");
back_print(root);
break;

case 4: *i=countleaf(root,i);
printf("\nThe tree have %d leafage.\n",*i);
*i=0;
break;
case 5: getchar();
printf("Please input the data you want to research: ");
x=getchar();
locate(root,x);
break;
case 6: depth=t_depth(root);
printf("The depth of the tree is %d.\n",depth);
break;

case 7:
break;
}
}
while(select<7);
printf("\n Press any key to quit...");
getch();
}

没有评论:

发表评论