让我们在ocaml中定义一个类型树。
type 'a tree =
T of 'a * 'a list;;
我想以两种方式遍历此图:(1)从根到叶子(2)从叶子到根
你能帮助我吗?
答案 0 :(得分:2)
type 'a tree = T of 'a * 'a tree list
let rec walk_downwards f = function
| T (elt, children) ->
f elt;
List.iter (walk_downwards f) children
let rec walk_upwards f = function
| T (elt, children) ->
List.iter (walk_upwards f) children;
f elt