我决定从http://rosettacode.org/wiki/Tree_traversal#C.2B.2B获取代码并使用 SDL 将其可视化。页面上的 ASCII 图形如下所示:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
但到目前为止我设法得到的结果看起来像:
ASCII:
1
2
4 3
7 6
8
9
注意缺少的 5。6 绘制在它上面(通过位置的调试输出验证。)
我的问题代码:
作为对指出错字的回应,我将从我的源文件中复制/粘贴原样:
void preorderTraverse(int x = osd.position.x, int y = osd.position.y) const {
osd.position.x = x;
osd.position.y = y;
std::cout << "Debug: " << x << " " << y << " " << getValue() << std::endl;
osd.put(getValue());
if(mLeft) { x -= 50; y += 30; mLeft->preorderTraverse(x, y);}
if(mRight) { x += 50; y += 30; mRight->preorderTraverse(x, y);}
}
这个想法是它遵循遍历的递归性质,但是当它遍历右侧时似乎有问题。
请注意,我将默认参数设置为 osd.position 因为它们是这样定义的:
position.x = SCREEN_WIDTH / 2 - 50/2;
position.y = 0;
osd.put 是:
SDL_Rect offset = get_offset(num);
SDL_BlitSurface( number_chart_, &offset, screen, &position );
offset 是源矩形(即,对图像进行blitting)。get_offset 只是对数字的sprite 表进行切片。
所以我的问题是如何修复 preorderTraverse 看起来像 ascii 图形?它不必做复杂的事情,例如检查整个树的宽度等,只需正确嵌套即可。