我正在尝试使用GraphViz为二进制搜索树重新创建示例图。最终应该是这样的:
这是我的第一次尝试:
digraph G {
nodesep=0.3;
ranksep=0.2;
margin=0.1;
node [shape=circle];
edge [arrowsize=0.8];
6 -> 4;
6 -> 11;
4 -> 2;
4 -> 5;
2 -> 1;
2 -> 3;
11 -> 8;
11 -> 14;
8 -> 7;
8 -> 10;
10 -> 9;
14 -> 13;
14 -> 16;
13 -> 12;
16 -> 15;
16 -> 17;
}
但是不幸的是GraphViz不在乎树的水平位置,所以我得到:
如何添加约束,以使顶点的水平位置反射(reflect)其总体顺序?
最佳答案
您可以按照通常的方法添加不可见的节点和不可见的边缘,并按照graphviz FAQ about balanced trees的建议使用边缘权重等。在一些simple cases中,这就足够了。
但是,有一个更好的解决方案:Graphviz附带了一个名为 gvpr (图形模式扫描和处理语言)的工具,该工具可以
而且自Emden R. Gansner did all the work already by creating a script which does layout nicely binary trees以来,这是如何做到的(所有功劳归功于ERG):
将以下gvpr脚本保存到名为tree.gv
的文件中:
BEGIN {
double tw[node_t]; // width of tree rooted at node
double nw[node_t]; // width of node
double xoff[node_t]; // x offset of root from left side of its tree
double sp = 36; // extra space between left and right subtrees
double wd, w, w1, w2;
double x, y, z;
edge_t e1, e2;
node_t n;
}
BEG_G {
$.bb = "";
$tvtype=TV_postfwd; // visit root after all children visited
}
N {
sscanf ($.width, "%f", &w);
w *= 72; // convert inches to points
nw[$] = w;
if ($.outdegree == 0) {
tw[$] = w;
xoff[$] = w/2.0;
}
else if ($.outdegree == 1) {
e1 = fstout($);
w1 = tw[e1.head];
tw[$] = w1 + (sp+w)/2.0;
if (e1.side == "left")
xoff[$] = tw[$] - w/2.0;
else
xoff[$] = w/2.0;
}
else {
e1 = fstout($);
w1 = tw[e1.head];
e2 = nxtout(e1);
w2 = tw[e2.head];
wd = w1 + w2 + sp;
if (w > wd)
wd = w;
tw[$] = wd;
xoff[$] = w1 + sp/2.0;
}
}
BEG_G {
$tvtype=TV_fwd; // visit root first, then children
}
N {
if ($.indegree == 0) {
sscanf ($.pos, "%f,%f", &x, &y);
$.pos = sprintf("0,%f", y);
}
if ($.outdegree == 0) return;
sscanf ($.pos, "%f,%f", &x, &y);
wd = tw[$];
e1 = fstout($);
n = e1.head;
sscanf (n.pos, "%f,%f", &z, &y);
if ($.outdegree == 1) {
if (e1.side == "left")
n.pos = sprintf("%f,%f", x - tw[n] - sp/2.0 + xoff[n], y);
else
n.pos = sprintf("%f,%f", x + sp/2.0 + xoff[n], y);
}
else {
n.pos = sprintf("%f,%f", x - tw[n] - sp/2.0 + xoff[n], y);
e2 = nxtout(e1);
n = e2.head;
sscanf (n.pos, "%f,%f", &z, &y);
n.pos = sprintf("%f,%f", x + sp/2.0 + xoff[n], y);
}
}
假设包含该图的点文件称为
binarytree.gv
,则可以执行以下行:dot binarytree.gv | gvpr -c -ftree.gv | neato -n -Tpng -o binarytree.png
结果是:
通过在脚本中切换一两行,您甚至可以使单个子节点位于左侧而不是右侧。
关于binary-tree - 在.dot树中强制执行水平节点排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10902745/