21

I am trying to recreate an example diagram for a binary search tree with GraphViz. This is how it should look in the end:

enter image description here

This is my first attempt:

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;
}

But unfortunately GraphViz doesn't care about the horizontal positions of the tree, so I get:

enter image description here

How can I add constraints so that the horizontal positions of the vertices reflects their total ordering?

4

1 回答 1

26

您可以按照graphviz 关于平衡树的常见问题解答中提出的添加不可见节点和不可见边的常用方法,以及使用边权重等。在一些简单的情况下,这就足够了。

但是有一个更好的解决方案:Graphviz 带有一个名为gvpr图形模式扫描和处理语言)的工具,它允许

将输入图复制到其输出,可能会转换其结构和属性,创建新图或打印任意信息

并且由于Emden R. Gansner 已经通过创建一个可以很好地布局二叉树的脚本完成了所有工作,下面是如何做到这一点(所有功劳归于 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

结果是:

多亏了 Emden R. Gansner,二叉树的布局很好,带有 graphiv 和 gvpr 脚本

通过在脚本中切换一两行,您甚至可以让单个子节点转到左侧而不是右侧。

于 2012-06-05T22:04:46.843 回答