OCaml:绘制二叉树

时间:2012-03-04 14:31:04

标签: tree ocaml draw

我正在使用树木制作一些程序。我想知道是否有任何代码可以在OCaml中绘制一般树。

type Tree = Node of Tree * int * Tree | Child of int;;

我在互联网上找到的只使用Caml Light,而不是客观Caml 提前谢谢。

2 个答案:

答案 0 :(得分:12)

你能用“画画”来澄清你的意思吗?我假设您正在考虑树的图形可视化?

我在使用工具graphviz使用的点格式生成图形/树形描述方面有相当不错的经验。我们的想法是你的OCaml程序以这种格式生成图形的文本表示,然后使用外部工具渲染它(将其转换为图像),并可能在屏幕上显示它。

Dot适用于一般图形。虽然您可能会发现具有更多功能的二叉树专用工具,但根据我的经验,它可以很好地适用于所有类型的树并显示通常您喜欢的内容。现在该工具并非没有缺陷,在某些情况下我遇到了错误(调用dot段错误)。我认为这仍然是一个合理的选择。

如何以dot格式具体输出:选择已存在的任何example图形,结构将非常明显:它只是一种文本格式。然后你编写运行在图形结构上的代码,用标签等正确的东西调用Printf,然后瞧。例如,this example看起来不错,here是源格式。我引用相关部分:

/* courtesy Ian Darwin and Geoff Collyer, Softquad Inc. */
digraph unix {
    size="6,6";
    node [color=lightblue2, style=filled];
    "5th Edition" -> "6th Edition";
    "5th Edition" -> "PWB 1.0";
    "6th Edition" -> "LSX";
    "6th Edition" -> "Interdata";
    "Interdata" -> "Unix/TS 3.0";
    "Interdata" -> "PWB 2.0";
    "Interdata" -> "7th Edition";
    "7th Edition" -> "8th Edition";
    "7th Edition" -> "32V";
    "7th Edition" -> "V7M";
    "V7M" -> "Ultrix-11";
    "8th Edition" -> "9th Edition";
    [...]
}

答案 1 :(得分:10)

如果简单且不太深,使用Graphics库来绘制树通常非常容易和有趣。

如果您想要文字表示:

type tree = Node of tree * int * tree | Child of int;;
let draw tree =
  let rec print indent tree =
    match tree with
       Child n -> 
        Printf.printf "%s%d\n" indent n
     | Node (left, n, right) ->
        Printf.printf "%s----\n" indent;
        print (indent ^ "| ") left;
        Printf.printf "%s%d\n" indent n;
        print (indent ^ "| ") right;
        Printf.printf "%s----\n" indent
  in
  print "" tree
相关问题