/*
面試(四)
開發環境:Visual Studio 2008
開發語言:C語言
要 求:
下列程序中的TreeSort函數功能:對任意已存在的二叉樹進行排序後生成一個新的二叉排序樹。 優化TreeSort函數:實現對任意已存的二叉樹進行排序(不允許在其過程中生成新樹)。
時 間:15-20分鐘
得分標準:
考覈標準: 口述算法思路不清晰者(0分)
考覈小組:張一濤
批註評語:
#include <stdio.h>
#include <stdlib.h>
typedef struct BTree
{
char data;
struct BTree *Lchild,*Rchild;
}Tree;
char data[100];
int k=0;
Tree *CreateTree(Tree *Root,char *str)
{
Tree *s[100],*p;
int i=0,k=0,top=0;
Root=NULL;
p=NULL;
for(i=0;str[i]!='\0';i++)
{
if(str[i]=='(')
{ s[top++]=p;k=1;}
else
if(str[i]==')')
top--;
else
if(str[i]==',')
k=2;
else
{
p=(Tree *)malloc(sizeof(Tree));
p->data=str[i];
p->Lchild=NULL;
p->Rchild=NULL;
if(Root==NULL)
Root=p;
else
{
if(k==1)
s[top-1]->Lchild=p;
else
s[top-1]->Rchild=p;
}
}
}
return Root;
}
void InOrder(Tree *r)
{
Tree *s[100],*p=r;
int top=-1;
while(p!=NULL||top!=-1)
{
while(p!=NULL)
{
s[++top]=p;
p=p->Lchild;
}
if(top!=-1)
{
p=s[top];
printf("%c ",p->data);
top--;
p=p->Rchild;
}
}
}
void FreeTree(Tree *R)
{
if(R!=NULL)
{
FreeTree(R->Lchild);
FreeTree(R->Rchild);
free(R);
}
}
void OutputByLayer(Tree *R)
{
Tree *Stack[100];
int cur =0,last = 0,tmp;
int high=0;
if(R==NULL)
return ;
Stack[last++]=R;
while(cur < last)
{
tmp=last;
while(cur < tmp)
{
printf("%c ",Stack[cur]->data);
data[k++]=Stack[cur]->data;
if(Stack[cur]->Lchild!=NULL)
Stack[last++]=Stack[cur]->Lchild;
if(Stack[cur]->Rchild!=NULL)
Stack[last++]=Stack[cur]->Rchild;
++cur;
}
printf("\n");
high++;
}
printf("The Tree is Node:%d\n",last);
printf("The Tree is high:%d\n",high);
data[k]='\0';
}
Tree *TreeSort(Tree *R)
{
Tree *p,*q,*t;
int i;
int flag;
if(k!=0||R==NULL)
{
t=(Tree *)malloc(sizeof(Tree));
t->data=data[0];
t->Lchild=NULL;
t->Rchild=NULL;
R=t;
}
for(i=1;i<k;i++)
{
t=(Tree *)malloc(sizeof(Tree));
t->data=data[i];
t->Lchild=NULL;
t->Rchild=NULL;
p=R;
q=R;
while(p!=NULL)
{
q=p;
if(t->data>=p->data)
{
flag=1;
p=p->Rchild;
continue;
}
if(t->data<p->data)
{
flag=0;
p=p->Lchild;
}
}
if(flag==0)
q->Lchild=t;
else
q->Rchild=t;
}
return R;
}
void main()
{
Tree *Root=NULL;
Tree *NewRoot=NULL;
printf("a(b(c,d(1,2)),e(,f(1,3)))\n");
Root=CreateTree(Root,"a(b(c,d(1,2)),e(,f(1,3)))");
printf("\nOutput By Layer:\n");
OutputByLayer(Root);
printf("\n");
printf("\n**********Binary-Sort-Tree**********\n");
printf("LayerTree:\t%s\n",data);
NewRoot=TreeSort(NewRoot);
printf("OrderTree:\t");
InOrder(NewRoot);
printf("\n");
printf("\nFreeTree!\n");
FreeTree(Root);
FreeTree(NewRoot);
}