数据过多或过长的话,显示的数字可能不正确(有的数据部分被挤掉,受限于控制台窗口的大小)
手动随机输入效果图
测试0-100之间数据,下面的数据部分被挤掉
#include "stdafx.h"
#include <Windows.h>
#include <math.h>
typedef struct tree_node{
struct tree_node *l;
struct tree_node *r;
ULONG data;
ULONG x;//行 从0开始 第x行有 2^x列 可存放的数据总大小:2^(x+1)-1
ULONG y;//列 从0开始
}TND;
//等比数列求和: a1(1-q^n)/(1-q)
//n行可存放的数据大小 1(1-2^n)/(1-2)=2^n-1
TND *rn=0;
TND* InsertTree(ULONG data,TND **node,ULONG x,ULONG y)
{
TND *tn=*node;
if(!tn){
tn=(TND*)malloc(sizeof(TND));
memset(tn,0,sizeof(TND));
tn->data=data;
tn->x=x;
tn->y=y;
*node=tn;
}else{
if(data>tn->data){//插到右边
InsertTree(data,&tn->r,++x,2*y+1);
}else if(data<tn->data){//插到左边
InsertTree(data,&tn->l,++x,2*y);
}else{
}
}
return tn;
}
int pTree(TND *node)
{
if(node){
printf("data=%d x=%d y=%d\n",node->data,node->x,node->y);
pTree(node->l);
pTree(node->r);
}
return 1;
}
int pTree2ByOrd(TND *node,int topY,int colNum,HANDLE outh)
{
char buf[64];
ULONG ret;
COORD cd={0};
CHAR_INFO ci={0};
if(node){
sprintf(buf,"%d",node->data);
cd.X=(node->y*2+1)*(colNum/pow((float)2,(int)node->x+1));
cd.Y=node->x+topY;
SetConsoleCursorPosition(outh,cd);
WriteConsole(outh,buf,strlen(buf),&ret,0);
//WriteConsoleOutput(outh,buf,
pTree2ByOrd(node->l,topY,colNum,outh);
pTree2ByOrd(node->r,topY,colNum,outh);
}
return 1;
}
int InsertArryToTree(int *ay,int aySize)//满二叉树插入,ay必须已经排序好,才能保证满二叉树,不然会溢出
{
int size=aySize/2;
if(aySize>1){
InsertTree(ay[size],&rn,0,0);
InsertArryToTree(ay,size);
if(aySize-size-1>0){
InsertArryToTree(ay+size+1,aySize-size-1);
}
}else{
InsertTree(*ay,&rn,0,0);
}
return 1;
}
int quicksort(int *ay,int aySize)
{
int i=0,j=aySize-1,tmp=ay[0],tmp2;
while(i<j){
while(i<j&&ay[j]>tmp){
j--;
}
if(i<j){
ay[i++]=ay[j];
}
while(i<j&&ay[i]<tmp){
i++;
}
if(i<j){
ay[j--]=ay[i];
}
}
if(i){//i==j
ay[i]=tmp;
}
if(i>1){
quicksort(ay,i);
}
if(aySize-i-1>1){
quicksort(ay+i+1,aySize-i-1);
}
return 1;
}
int pArry(int *ay,int aySize)
{
int i;
for(i=0;i<aySize;i++){
printf("ay[%d]=%d\n",i,ay[i]);
}
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
char buf[256]={0};
int i,max=100,*ay=0,ay2[100];
CONSOLE_SCREEN_BUFFER_INFO csbi={0};
HANDLE out=GetStdHandle(STD_OUTPUT_HANDLE);
printf("输入要插入树中数据,q键退出\n");
i=0;
while(strcmp(gets(buf),"q")){
ay2[i]=strtoul(buf,0,10);
i++;
if(i>sizeof(ay2)/sizeof(ay2[0])){
break;
}
}
quicksort(ay2,i);//排序是为了满二叉树插入
//pArry(ay2,i);
InsertArryToTree(ay2,i);
/*
ay=(int*)malloc(sizeof(int)*max);
for(i=0;i<max;i++){
ay[i]=i;
}
InsertArryToTree(ay,max);
*/
printf("tree:%p \n",rn);
pTree(rn);
printf("树形图:\n");
GetConsoleScreenBufferInfo(out,&csbi);
pTree2ByOrd(rn,csbi.dwCursorPosition.Y,csbi.dwSize.X,out);
//printf("按任何键退出程序!\n");
getchar();
return 0;
}