2 个解决方案
#1
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *lchild,*rchild;
}BSTNode;
BSTNode *insert(BSTNode *t,BSTNode *s)
{
BSTNode *p,*q; //p指向欲插入的节点,q指向p节点的父节点
if(t==NULL) return s;
p=t; //p指向根节点
while(p) //使q成为s的父节点,p指向s的位置
{
q=p;
if(s->data==p->data)
{
return t;
}
if(s->data >p->data)
{
p=p->rchild;
}
else
p=p->lchild;
}
if(s->data >q->data)
{
q->rchild=s;
}
else
q->lchild=s;
return t;
}
BSTNode *create()
{
BSTNode *t,*s;
int e;
t=NULL;
scanf("%d",&e);
while(e!=-1)
{
BSTNode *s=(BSTNode *)malloc(sizeof(BSTNode));
s->lchild =NULL;
s->rchild =NULL;
s->data =e;
t=insert(t,s);
scanf("%d",&e);
}
return t;
}
void InOrder(BSTNode *t)
{
if(t)
{
InOrder(t->lchild );
printf("%d,",t->data );
InOrder(t->rchild );
}
}
#include <stdlib.h>
typedef struct node
{
int data;
struct node *lchild,*rchild;
}BSTNode;
BSTNode *insert(BSTNode *t,BSTNode *s)
{
BSTNode *p,*q; //p指向欲插入的节点,q指向p节点的父节点
if(t==NULL) return s;
p=t; //p指向根节点
while(p) //使q成为s的父节点,p指向s的位置
{
q=p;
if(s->data==p->data)
{
return t;
}
if(s->data >p->data)
{
p=p->rchild;
}
else
p=p->lchild;
}
if(s->data >q->data)
{
q->rchild=s;
}
else
q->lchild=s;
return t;
}
BSTNode *create()
{
BSTNode *t,*s;
int e;
t=NULL;
scanf("%d",&e);
while(e!=-1)
{
BSTNode *s=(BSTNode *)malloc(sizeof(BSTNode));
s->lchild =NULL;
s->rchild =NULL;
s->data =e;
t=insert(t,s);
scanf("%d",&e);
}
return t;
}
void InOrder(BSTNode *t)
{
if(t)
{
InOrder(t->lchild );
printf("%d,",t->data );
InOrder(t->rchild );
}
}
#2
谢谢仁兄出手相助!
#1
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *lchild,*rchild;
}BSTNode;
BSTNode *insert(BSTNode *t,BSTNode *s)
{
BSTNode *p,*q; //p指向欲插入的节点,q指向p节点的父节点
if(t==NULL) return s;
p=t; //p指向根节点
while(p) //使q成为s的父节点,p指向s的位置
{
q=p;
if(s->data==p->data)
{
return t;
}
if(s->data >p->data)
{
p=p->rchild;
}
else
p=p->lchild;
}
if(s->data >q->data)
{
q->rchild=s;
}
else
q->lchild=s;
return t;
}
BSTNode *create()
{
BSTNode *t,*s;
int e;
t=NULL;
scanf("%d",&e);
while(e!=-1)
{
BSTNode *s=(BSTNode *)malloc(sizeof(BSTNode));
s->lchild =NULL;
s->rchild =NULL;
s->data =e;
t=insert(t,s);
scanf("%d",&e);
}
return t;
}
void InOrder(BSTNode *t)
{
if(t)
{
InOrder(t->lchild );
printf("%d,",t->data );
InOrder(t->rchild );
}
}
#include <stdlib.h>
typedef struct node
{
int data;
struct node *lchild,*rchild;
}BSTNode;
BSTNode *insert(BSTNode *t,BSTNode *s)
{
BSTNode *p,*q; //p指向欲插入的节点,q指向p节点的父节点
if(t==NULL) return s;
p=t; //p指向根节点
while(p) //使q成为s的父节点,p指向s的位置
{
q=p;
if(s->data==p->data)
{
return t;
}
if(s->data >p->data)
{
p=p->rchild;
}
else
p=p->lchild;
}
if(s->data >q->data)
{
q->rchild=s;
}
else
q->lchild=s;
return t;
}
BSTNode *create()
{
BSTNode *t,*s;
int e;
t=NULL;
scanf("%d",&e);
while(e!=-1)
{
BSTNode *s=(BSTNode *)malloc(sizeof(BSTNode));
s->lchild =NULL;
s->rchild =NULL;
s->data =e;
t=insert(t,s);
scanf("%d",&e);
}
return t;
}
void InOrder(BSTNode *t)
{
if(t)
{
InOrder(t->lchild );
printf("%d,",t->data );
InOrder(t->rchild );
}
}
#2
谢谢仁兄出手相助!