简体   繁体   中英

How to pass a binary tree for a list of lists in OCaml?

i need to pass a binary tree for a list of lists but do not know how to proceed. Any suggestion?

The usual way to view a tree structure (or more generally a forest) as a list of list is its "paths representation". You can represent a binary tree as the data of all the paths from the root to the leaves (so you have as many paths as leaves in your tree).

Example:

      /\
     /  \
    /    \
   /\    /\
    /\  /\
         /\

May be represented as the following list:

  1. Left, Left
  2. Left, Right, Left
  3. Left, Right, Right
  4. Right, Left, Left
  5. Right, Left, Right, Left
  6. Right, Left, Right, Right
  7. Right, Right

There are many variations of this representation. For instance, when the nodes carry information it is easier to represent the graph as the list of paths to each node (and not only to the leaves). So you will probably need to adapt this answer to solve your particular problem.

This may be built up by traversing your tree in a depth-first fashion. Conversely, you can then reconstruct your tree from the list of paths recursively.

type binary_tree =
  | Empty
  | Node of binary_tree * binary_tree

type branch =
  | Left
  | Right

let rec to_paths tree =
  match tree with
  | Empty -> [[]]
  | Node (left, right) ->
      (List.map (fun l -> Left :: l) (to_paths left))
    @ (List.map (fun l -> Right :: l) (to_paths right))

let rec of_paths = function
  | [[]] -> Empty
  | l ->
    let lefts, rights = List.partition (function
       | [] -> failwith "of_paths: not at binary tree"
       | Left :: _ -> true
       | Right :: _ -> false) l
    in
    Node (of_paths (List.map List.tl lefts),
          of_paths (List.map List.tl rights))

(* A little test : *)    
let tree =
  Node (Node(Empty, Node (Empty, Empty)),
        Node (Node(Empty, Node (Empty, Empty)), Empty))

let () = assert (tree = of_paths (to_paths tree))

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