繁体   English   中英

如何在OCaml中为列表列表传递二叉树?

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

我需要为列表列表传递二叉树,但不知道如何进行。 有什么建议吗?

将树结构(或更一般的森林)视为列表列表的常用方法是其“路径表示”。 您可以将二叉树表示为从根到叶子的所有路径的数据(因此您的路径与树中的叶子一样多)。

例子:

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

可以表示为以下列表:

  1. 左,左
  2. 左,右,左
  3. 左,右,右
  4. 右,左,左
  5. 右,左,右,左
  6. 右,左,右,右
  7. 是的是的

这种表示有许多变体。 例如,当节点携带信息时,更容易将图表示为到每个节点(而不仅仅是到叶子)的路径列表。 因此,您可能需要调整此答案以解决您的特定问题。

这可以通过以深度优先的方式遍历您的树来建立。 相反,您可以递归地从路径列表中重建您的树。

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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