Recursion OCaml树遍历-如何遍历多路树
如何使用以下类型定义从叶子到顶部遍历多路树Recursion OCaml树遍历-如何遍历多路树,recursion,tree,ocaml,traversal,Recursion,Tree,Ocaml,Traversal,如何使用以下类型定义从叶子到顶部遍历多路树 type tree = Branch of float * tree list | Leaf 与遍历二叉树的方法相同,只是需要使用List.fold_left(或其他适当的列表迭代器)遍历子树。总纲如下: let rec traverse work tree = match tree with | Leaf -> ... do the leaf work and add it to `work`... | Branch (w,trees) -
type tree = Branch of float * tree list | Leaf
与遍历二叉树的方法相同,只是需要使用
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
,这样您就可以在transverse
内部使用transverse
work
参数保存已遍历节点所做的功我会逐一提出建议。你试过了吗?也许给我们看一段你试过的代码,然后我们可以帮助理解为什么它不起作用?要在节点值之前处理叶子,首先遍历列表,然后处理节点的值。