如何从叶子到顶部遍历具有以下类型定义的多路树
type tree = Branch of float * tree list | Leaf
答案 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 ...
关键时刻:
rec
这样你就可以在 traverse
中使用 traverse
work
参数保存已遍历节点完成的工作