在二叉树中查找值为x的结点,编写程序输出值为x的结点的所有祖先,

2024-12-18 00:42:24
推荐回答(1个)
回答1:

您好,这样的:
#include"stdio.h"
typedef struct node
{ int data;
struct node *left,*right;
}ErXTree;
void insert(ErXTree **t,ErXTree *s)
{ if(*t==NULL) *t=s;
else if(s->data==(*t)->data) return;
else if(s->data<(*t)->data) insert(&(*t)->left,s);
else if(s->data>(*t)->data) insert(&(*t)->right,s);
}
void creat(ErXTree **t1)
{ int x;
ErXTree *s;
printf("please input number:\n");
scanf("%d",&x);
while(x!=0)
{ s=(ErXTree*)malloc(sizeof(ErXTree));
s->data=x;
s->left=NULL;
s->right=NULL;
insert(t1,s);
s=NULL;
printf("please input number(0 is end):\n");
fflush(stdin);
scanf("%d",&x);}
}
int search(ErXTree *b,int x)
{
if(b==NULL) return NULL;
else
{if(b->data==x)
{return b->data;
}
else
{if(xdata)
{printf("zu xian shi:%d",b->data);
return search(b->left,x);
}
else
{
printf("%d",b->data);
return search(b->right,x);
}}}}
main()
{
ErXTree *t=NULL;
int x;
creat(&t);
printf("input:\n");
scanf("%d",&x);
search(t,x);
}