简体   繁体   中英

Ocaml list to tree

I want to write a function load: 'a option list -> 'a tree , that restores binary tree from the given list, which contains the elements in postfix order. If the list does not represent any tree, your function should raise the exception Load (you have to declare it earlier).

The tree is defined as :

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

So far what I did was :

exception Load ;;

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

Here's an example of an Input list:

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

It's kind of tricky how to do it. Since the list is in postfix order, I'm wondering if it will be better to use List.foldright function ??

I think you should try harder to do your homework (surely there is something interesting to learn), but as you apparently don't care:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM