使用 (y, x) 坐标
C代码在这里:
void printVLine(wchar_t token, unsigned short height, unsigned short y, unsigned short x);
const static wchar_t TREE_VLINE = L'┃';
const static wchar_t TREE_INBRANCH[] = L"┣╾⟶ ";
const static wchar_t TREE_OUTBRANCH[] = L"┗╾⟶ ";
typedef void (*Printer)(void * whateverYouWant);
const static unsigned int INBRANCH_SIZE = sizeof(TREE_INBRANCH) / sizeof(TREE_INBRANCH[0]);
const static unsigned int OUTBRANCH_SIZE = sizeof(TREE_OUTBRANCH) / sizeof(TREE_OUTBRANCH[0]);
size_t Tree_printFancy(Tree * self, int y, int x, Printer print){
if (self == NULL) return 0L;
//
size_t descendants = y;
move(y, x);
print(Tree_at(self));
if (!Tree_isLeaf(self)){ // in order not to experience unsigned value overflow in while()
move(++y, x);
size_t i = 0;
while(i < Tree_childrenSize(self) - 1){
wprintf(TREE_INBRANCH);
size_t curChildren = Tree_printFancy(
Tree_childAt(self, i), y, x + INBRANCH_SIZE, print
);
printVLine(TREE_VLINE, curChildren , y + 1, x);
move((y += curChildren), x);
++i;
}
wprintf(TREE_OUTBRANCH);
y += Tree_printFancy( // printing outermost child
Tree_childAt(self, i), y, x + OUTBRANCH_SIZE, print
) - 1;
}
return y - descendants + 1;
}
它适用于控制台打印。函数 move(y, x) 将光标移动到屏幕上的 (y, x) 位置。最好的部分是,您可以通过更改变量 TREE_VLINE、TREE_INBRANCH、TREE_OUTBRANCH 来更改输出样式,最后两个字符串的长度无关紧要。你可以打印任何你喜欢的东西,通过传递打印机函数指针,它将打印当前树节点的值。输出看起来像这样