二叉树图形显示

代码:

#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");
	}
}

图片:

  • 5
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值