Re: 想要把一棵二叉树图形输出,请问有什么好算法?(xiaochangzi)
不好意思,昨天因为没有在机器上调试,所以代码有些混乱,现在把调试通过的详细代码贴出来共享,另有MFC demo,需要的把email给出来:(我本想发在原贴里面,但是系统提示我回复太多,所以只好另开一贴)
typedef struct BITREENODE
{
BITREENODE* lchild;
BITREENODE* rchild;
} *PBITREENODE, *LPBITREENODE;
CDC* dc = NULL;
int x, y;
LPBITREENODE root = NULL;
void CreateTree()
{
// add code to create tree here
}
int DrawTree(LPBITREENODE parent)
{
int rdy = 1; // parent need 1 layer
int ldy = 0;
DrawNode(parent);
if (parent->rchild != NULL)
{
DrawLink(-1);
x++;
rdy = DrawTree(parent->rchild);
x--;
}
if (parent->lchild != NULL)
{
DrawLink(rdy);
x++, y += rdy;
ldy = DrawTree(parent->lchild);
y -= rdy, x--;
}
return rdy + ldy;
}
void DrawNode(LPBITREENODE node)
{
if (dc == NULL) return;
rc.SetRect(x*20, y*20, x*20+10, y*20+10);
dc->Rectangle(&rc);
}
void DrawLink(int dy)
{
if (dc == NULL) return;
int a, b; // POINT(a, b)
int c, d; // POINT(c, d)
if (dy < 0)
{
a = x*20+10, b = y*20+5;
c = a+10, d = b;
dc->MoveTo(a, b);
dc->LineTo(c, d);
}
else
{
a = x*20+5, b = y*20+10;
c = a, d = b+dy*20-5;
dc->MoveTo(a, b);
dc->LineTo(c, d);
c += 15;
dc->LineTo(c, d);
}
}
void Show(CDC* pDC)
{
dc = pDC;
if (root != NULL)
{
x = 0, y = 0;
DrawTree(root);
}
dc = NULL;
}