1

我想写一个函数load: 'a option list -> 'a tree,从给定的列表中恢复二叉树,其中包含后缀顺序的元素。如果列表不代表任何树,您的函数应该引发异常 Load(您必须提前声明它)。

树定义为:

type ‘a btree = L of ‘a | N of ‘a btree * ‘a btree

到目前为止,我所做的是:

exception Load ;;

let rec load l =
    match l with
        | [] -> raise Load
        | Some x::_ -> L x
        | None::t -> N(?,load t)
;; 

这是输入列表的示例:

[Some 2; Some 0; None; Some 5; Some 9; Some 20; None; None; None]

如何做到这一点有点棘手。由于列表是按后缀顺序排列的,我想知道使用List.foldright函数是否会更好?

4

1 回答 1

6

我认为您应该更加努力地完成作业(肯定有一些有趣的东西要学习),但是您显然不在乎:

let load input =
  let rec load stack = function
    | [] -> stack
    | Some elem :: rest -> load (L elem :: stack) rest
    | None :: rest ->
      match stack with
        | right :: left :: stack -> load (N(left, right) :: stack) rest
        | [] | [_] -> failwith "incorrect node arity"
  in
  match load [] input with
    | res :: [] -> res
    | [] -> failwith "no input"
    | _ :: _ :: _ -> failwith "remaining nodes"
于 2012-05-29T15:21:35.530 回答