第1个回答 2011-05-23
#include <stdio.h>//二叉树排序
#include <stdlib.h>
typedef struct btree//结构
{
int a;
struct btree *L;
struct btree *R;
};
btree *create(int n)//建表
{
if(--n){
btree *p;
p=(btree *)malloc(sizeof(btree));
p->a=n;
p->L=create(n);
p->R=create(n);
return p;
}
else return NULL;
}
void commute(btree *p,btree *pre)//交换两个数的值
{
int t;
t=p->a;
p->a=pre->a;
pre->a=t;
}
void endpre(btree *p,btree *pre)//后序遍历 +排序
{
if(p){
endpre(p->L,p);//pre保持指向p的上层...
endpre(p->R,p);
if(pre->a > p->a)commute(pre,p);//孩子父母对换..
}
}
void headpre(btree *p)//前序遍历
{
if(p){
printf("%d ",p->a);
headpre(p->L);
headpre(p->R);
}
}
void depth(btree *p,int lev,int *pe)//求二叉树深度
{
if(p){
if(lev>*pe)*pe=lev;
depth(p->L,lev+1,pe);
depth(p->R,lev+1,pe);
}
}
int main()
{
btree *p;
int n,i=1,j=0;
scanf("%d",&n);
p=create(n);
headpre(p);
printf("\n");
depth(p,i,&j);//求二叉树深度
for(;j>0;j--)endpre(p,p);//这个循环次数为二叉树深度减一
headpre(p);
system("pause");
return 0;