GCC编译通过:
#include <stdio.h>
#include <stdlib.h>
#define N 10
#define MAX 100
typedef struct node{
int data;
struct node *left;
struct node *right;
}BTnode;
BTnode *queue[N+1];
int rear=0,front=0;
void PHeap(BTnode *r)
{
BTnode *t;
int flag=1;
int tt,k;
while(flag){
flag=0;
for(t=queue[front],k=front;k;k--){
t=queue[k];
if(t->left->data>t->data){
tt=t->data;
t->data=t->left->data;
t->left->data=tt;
flag=1;
}
if(t->right&&t->right->data>t->data){
tt=t->data;
t->data=t->right->data;
t->right->data=tt;
flag=1;
}
}//for
}//while(flag)
}
BTnode *Sort(BTnode *root)
{
while(front>=1){
PHeap(root);
printf("%5d",root->data);
root->data=queue[rear]->data;
if(rear%2) queue[rear/2]->right=NULL;
else{
queue[rear/2]->left=NULL;
if(front==1) printf("%5d",root->data);
front--;
}
rear--;
}
}
BTnode *deal(int a[],int n)
{
int i;
BTnode *root;
/*按层,使用队列*/
for(i=0;i<n;i++){
/*初始化新节点*/
BTnode *t=(BTnode *)malloc(sizeof(BTnode));
t->left=t->right=NULL;
t->data=a[i];
/*入队*/
queue[++rear]=t;
if(i==0){
root=t;
front++;
}else{
if(!queue[front]->left){
queue[front]->left=t;
}else{
queue[front]->right=t;
front++;
}
}
}
return root;
}
/*按层输出二叉树*/
void PrintTree(BTnode *root)
{
BTnode *t=NULL;
BTnode *queue[MAX];
int front=0,rear=0;
/*入队*/
queue[++rear]=root;
/*出队*/
while(front!=rear){
t=queue[++front];
printf("%d",t->data);
if(t->left) queue[++rear]=t->left;
if(t->right) queue[++rear]=t->right;
}
putchar('
');
}
int main(void)
{
int a[N]={1,3,5,7,9,2,4,6,8,10};
BTnode *root=NULL;
root=deal(a,N);
PrintTree(root);
Sort(root);
return 0;
}