程序的核心思想:http://wenku.baidu.com/link?url=c9yGE_yu-PLWNVq8IB2Lmd96-vpI5Vp0n23-FwywOXKmo3VZ1rmXGRLQ4BzGRTq_Y59Ps3lEegveMU5zYq1S846grtXGYt8DyagZWEvHa0i
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <list>
#include <algorithm>
#include "SearchTree.h"
#include <graphics.h>
#include <string>
#include <conio.h>
using namespace std;
void Tree2Nodes(SearchTree T, int nodes[][4], int k = 1) //数组从1开始编号,不能从0开始
{
if(T != NULL)
{
Tree2Nodes(T->Left, nodes, 2*k);
nodes[k][2] = 1;
nodes[k][3] = T->Element;
Tree2Nodes(T->Right, nodes, 2*k + 1);
}
}
void Draw(SearchTree T, int nodes[][4], int radius, int k = 1)
{
if(T != NULL)
{
Draw(T->Left, nodes, radius, 2 * k);
setlinecolor(BLUE);
circle(nodes[k][0], nodes[k][1], radius);
char s[10];
sprintf(s, "%d", nodes[k][3]);
settextstyle(2 * radius, 0, _T("宋体"));
outtextxy(nodes[k][0] + radius + 1, nodes[k][1] - radius, s);
setlinecolor(YELLOW);
if(nodes[2 * k][2] == 1)
line(nodes[k][0], nodes[k][1] + radius, nodes[2 * k][0], nodes[2 * k][1] - radius);
if(nodes[2 * k + 1][2] == 1)
line(nodes[k][0], nodes[k][1] + radius, nodes[2 * k + 1][0], nodes[2 * k + 1][1] - radius);
Draw(T->Right, nodes, radius, 2 * k + 1);
}
}
void DisplayTree(SearchTree T)
{
int width = 640 / (pow(2, Depth(T) - 1) + 1), height = 0.85 * 480 / (Depth(T) - 1); //作图区的宽640,高480
int radius = 0.125 * width;
int nodes[1024][4] = {0}; //最多可以输出10层的树
int depth = Depth(T);
Tree2Nodes(T, nodes);
for(int i = depth; i >= 1; i--)
{
int first; //每一层中,首结点的横坐标
if(i == depth)
first = width;
else
first = (int)(pow(2, depth - i - 1)*width + width / 2);
int w; //每一层中,相邻两结点的距离
w = (int)(pow(2, depth - i) * width);
for(int j = (int)(pow(2, i - 1)); j <= (int)(pow(2, i) - 1); j++)
{
if(nodes[j][2] == 1)
{
nodes[j][0] = (int)(first + (j - pow(2, i - 1)) * w);
nodes[j][1] = height * (i - 1) + radius;
}
}
}
Draw(T, nodes, radius);
}
int main()
{
SearchTree T = NULL;
T = Insert(20, T);
T = Insert(10, T);
T = Insert(30, T);
initgraph(640, 480);
DisplayTree(T);
getch();
closegraph();
return 0;
}