Joã*_*ira 1 tree ocaml list tree-traversal
我想编写一个函数load: 'a option list -> 'a tree,它从给定列表中恢复二进制树,其中包含后缀顺序的元素.如果列表不代表任何树,则您的函数应该引发异常Load(您必须先声明它).
树被定义为:
type ‘a btree = L of ‘a | N of ‘a btree * ‘a btree
Run Code Online (Sandbox Code Playgroud)
到目前为止,我所做的是:
exception Load ;;
let rec load l =
match l with
| [] -> raise Load
| Some x::_ -> L x
| None::t -> N(?,load t)
;;
Run Code Online (Sandbox Code Playgroud)
以下是输入列表的示例:
[Some 2; Some 0; None; Some 5; Some 9; Some 20; None; None; None]
Run Code Online (Sandbox Code Playgroud)
如何做到这一点真是太棘手了.由于列表是后缀顺序,我想知道是否更好地使用List.foldright函数??
我认为你应该更加努力地完成你的作业(当然有一些有趣的东西需要学习),但是你显然不在乎:
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"
Run Code Online (Sandbox Code Playgroud)