OCaml - 遍历一棵树

时间:2013-10-24 12:39:06

标签: tree ocaml

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

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

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

你能帮助我吗?

1 个答案:

答案 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
相关问题