反过来做:计算每个节点的水平位置后,计算其子节点的水平位置。像这样的东西(警告:完全未经测试的代码;可能完全由错误组成):
void Node::place_self(coord_t x0, coord_t y0) {
this->y0 = y0; this->y1 = y0+height;
if (!left && !right) {
// This is a leaf. Put its top left corner at (x0,y0).
this->x0 = x0; this->y0 = y0;
this->subtree_x1 = x0+width;
}
else if (!left || !right) {
// Only one child. Put this immediately above it.
Node * child = left ? left : right;
child->place_self(x0,y0+height+gap);
coord_t xc = child->x0 + child->width/2;
this->x0 = xc-width/2;
this->subtree_x1 = max(this->x0+width, child->subtree_x1);
}
else {
// Two children. Put this above their midline.
left->place_self(x0, y0+height+gap);
right->place_self(left->subtree_x1+gap, y0+height+gap);
coord_t xc = (x0 + right->subtree_x1)/2;
this->x0 = xc-width/2;
this->subtree_x1 = max(this->x0+width, right->subtree_x1);
}
}