【问题标题】:Ocaml list to treeOcaml 列表到树
【发布时间】:2012-05-29 12:53:00
【问题描述】:

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

树定义为:

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函数是否会更好??

【问题讨论】:

    标签: list tree ocaml tree-traversal


    【解决方案1】:

    我认为你应该更加努力地做功课(肯定有一些有趣的东西要学),但你显然不在乎:

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多