OCaml 树遍历 - 我如何遍历多路树

时间:2021-02-02 09:34:24

标签: recursion tree ocaml traversal

如何从叶子到顶部遍历具有以下类型定义的多路树

type tree = Branch of float * tree list | Leaf

1 个答案:

答案 0 :(得分:2)

与遍历二叉树的方式相同,只是需要使用 List.fold_left(或其他合适的列表迭代器)来遍历子树。以下是大纲,

let rec traverse work tree = match tree with 
| Leaf -> ... do the leaf work and add it to `work`...
| Branch (w,trees) -> 
  let r = List.fold_left traverse work trees in
  ... finish the branch work ...

关键时刻:

  1. 不要忘记 rec 这样你就可以在 traverse 中使用 traverse
  2. work 参数保存已遍历节点完成的工作
  3. 最终结果应是所有节点完成的工作的总和(达到总和的某个定义)。