您的位置:首页 > 职场人生

二叉排序树(面试四)

2016-06-13 19:57 330 查看
/*

面试(四)

开发环境: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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: