-2

让我们在 ocaml 中定义一个类型树。

type 'a tree = 
 T of 'a * 'a list;;

我想以两种方式遍历此图:(1)从根到叶(2)从叶到根

你能帮助我吗?

4

1 回答 1

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
于 2013-10-24T13:13:59.767 回答