代码:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXROW 100
#define MAXCOL 100
typedef struct bitnode
{
char data;
struct bitnode *left,*right;
}bitnode,*bitree;
bitree create(bitree t)
{
char ch;
scanf("%c",&ch);
if(ch=='#')
t=NULL;
else
{
if(!(t=(bitnode*)malloc(sizeof(bitnode))))
printf("overflow\n");
t->data=ch;
t->left=create(t->left);
t->right=create(t->right);
}
return t;
}
void look(bitree root)
{
if(root!=NULL)
{
printf("%c",root->data);
look(root->left);
look(root->right);
}
}
int calc_tree_layers(bitree root)
{
int left_way_layers,right_way_layers;
if(root==NULL)
return 0;
else
{
left_way_layers=1+calc_tree_layers(root->left);
right_way_layers=1+calc_tree_layers(root->right);
if(left_way_layers>right_way_layers)
return left_way_layers;
else
return right_way_layers;
}
}
char dispbuf[MAXROW][MAXCOL];
void start()
{
int i,j;
for(i=0;i<MAXROW;i++)
{
for(j=0;j<MAXCOL;j++)
dispbuf[i][j]=' ';
}
}
int effective_line=0;
void perfect()
{
int i,j;
for(i=0;i<MAXROW;++i)
{
j=MAXCOL-1;
while(dispbuf[i][j]==' '&&j>=0)
--j;
if(j>-1)
{
dispbuf[i][j+1]='|';
++effective_line;
continue;
}
else
break;
}
}
void print_tree(bitnode *root,int root_x,int root_y,int r_c_interval,char disp_buf[][MAXCOL])
{
int left_child,right_child,y;
if(root!=NULL)
{
if(r_c_interval!=3)
{
r_c_interval/=2;
left_child=root_x-r_c_interval;
right_child=root_x+r_c_interval;
}
else
{
left_child=root_x-2;
right_child=root_x+2;
}
disp_buf[root_y][root_x]=root->data;
if(root->left!=NULL)
disp_buf[root_y+1][root_x-1]='/';
if(root->right!=NULL)
disp_buf[root_y+1][root_x+1]='\\';
root_y+=2;
print_tree(root->left,left_child,root_y,r_c_interval,disp_buf);
print_tree(root->right,right_child,root_y,r_c_interval,disp_buf);
}
}
int main()
{
int i,j;
bitree root=NULL;
printf("请输入二叉树先序序列:\n");
root=create(root);
int tree_layers=calc_tree_layers(root);
printf("该二叉树共有%d层\n",tree_layers);
int root_x=3*pow(2,tree_layers-2),root_y=0,r_c_interval=3*pow(2,tree_layers-2);
start();
print_tree(root,root_x,root_y,r_c_interval,dispbuf);
perfect();
printf("hello,I am the binary tree!\n");
for(i=0;i<effective_line;++i)
{
for(j=0;j<MAXCOL;++j)
{
if(dispbuf[i][j]!='|')
printf("%c",dispbuf[i][j]);
else
break;
}
printf("\n");
}
}
图片: