#include<stdio.h>
#include<iostream.h>
#include<string.h>
#include<malloc.h>
typedef struct node
{char name;
int age;
struct node *lchild;
struct node *rchild;
}BTNode;
struct data //定义输入数据类型
{int key;
char n;
};
int InsertBT(BTNode *&p,data); //插入结点
void CreateBTNode(BTNode *&b,int i); //创建二叉树
void DispBTNode(BTNode *b); //括号表示法输出二叉树b
int BTNodeDepth(BTNode *b); //输出二叉树b的深度
void AgeMin(BTNode *b); //查找并输出年龄最小的元素
void AgeMax(BTNode *b); //查找并输出年龄最大的元素
void main()
{BTNode *b;
data t;
cout<<"(1)输入12个数据并生成二叉树b(先名后龄):"<<endl;
CreateBTNode(b,12);
cout<<"(2)括号表示法输出二叉树b:"<<endl;
DispBTNode(b);
cout<<"(3)二叉树b的深度:"<<BTNodeDepth(b)<<endl;
cout<<"(4)年龄最小的元素:";AgeMin(b);
cout<<"(5)年龄最大的元素:";AgeMax(b);
cout<<"(6)插入{'郭',40}:";
cin>>t.key>>t.n;
InsertBT(b,t);
DispBTNode(b);
}
int InsertBT(BTNode *&p,data e)
{if(p==NULL)
{p=(BTNode*)malloc(sizeof(BTNode));
p->age=e.key;p->name=e.n;
p->lchild=p->rchild=NULL;
return 1;
}
else if(e.key==p->age) return 0; //有相同关键字结点,返回0
else if(e.key<=p->age) return InsertBT(p->lchild,e); //插入*p的左子树中
else return InsertBT(p->rchild,e); //插入*p的右子树中
}
void CreateBTNode(BTNode *&p,int i)
{BTNode *b=NULL;
int j,k=0;
data d[12];
for(j=0;j<i;j++)
cin>>d[j].n>>d[j].key;
while(k<i)
{InsertBT(b,d[k]);
k++;
}
}
void DispBTNode(BTNode *b)
{if(b!=NULL)
{cout<<b->name;
if(b->lchild!=NULL||b->rchild!=NULL)
{cout<<"(";
DispBTNode(b->lchild);
if(b->rchild!=NULL)cout<<",";
DispBTNode(b->rchild);
cout<<")";
}
}
}
int BTNodeDepth(BTNode *b)
{int lchilddep,rchilddep;
if(b==NULL) return(0);
else
{lchilddep=BTNodeDepth(b->lchild);
rchilddep=BTNodeDepth(b->rchild);
return(lchilddep>rchilddep)?(lchilddep+1):(rchilddep+1);
}
}
void AgeMin(BTNode *b)
{if(b->lchild!=NULL)AgeMin(b->lchild);
else
cout<<b->name<<" "<<b->age<<endl;
}
void AgeMax(BTNode *b)
{if(b->rchild!=NULL)AgeMax(b->rchild);
else
cout<<b->name<<" "<<b->age<<endl;
}
如输入:
{“张”, 25}, {“王”, 18}, {“钟”, 2}, {“陈”, 46}, {“李”,53}, {“吴”, 39}, {“刘”, 4}, {“邓”, 74}, {“陆”, 32}, {“丁”, 11}, {“蒋”, 67}, {“洪”, 60},以age为关键字
慕容708150