发布网友 发布时间:2022-04-25 12:37
共1个回答
热心网友 时间:2023-07-13 16:59
#include <stdio.h>
#include <stdlib.h>
typedef struct bnode
{
int data;
struct bnode *left , *right ;
} btree ;
void insert(btree **b , btree *s)
{
if(*b==NULL) *b = s ;
else if((*b)->data == s->data)
return ;
else if(s->data > (*b)->data)
insert(&(*b)->right , s);
else if(s->data < (*b)->data)
insert(&(*b)->left , s);
}
void creatTree(btree **b)
{
int x ;
btree *s ;
*b = NULL ;
do
{
printf("Input data please : ");
scanf("%d",&x);
s = (btree *)malloc(sizeof(btree)) ;
s->data = x ;
s->left = NULL ;
s->right = NULL ;
insert( b , s );
} while(x != 0 );
}
void print(btree *b)
{
if (b != NULL)
{
printf("%d",b->data);
if (b->left != NULL || b->right != NULL)
{
printf("(");
print(b->left);
if(b->right != NULL)
printf(", ");
print(b->right);
printf(")");
}
}
}
void preorder(btree *b)
{
if (b!=NULL)
{
printf("%d",b->data);
preorder(b->left);
preorder(b->right);
}
}
void main()
{
btree *t = NULL;
creatTree(&t);
printf("The binary tree is : ");
print(t);
printf("\n");
preorder(t);
printf("\n");
}