[英]How to pass a binary tree for a list of lists in OCaml?
我需要為列表列表傳遞二叉樹,但不知道如何進行。 有什么建議嗎?
將樹結構(或更一般的森林)視為列表列表的常用方法是其“路徑表示”。 您可以將二叉樹表示為從根到葉子的所有路徑的數據(因此您的路徑與樹中的葉子一樣多)。
例子:
/\
/ \
/ \
/\ /\
/\ /\
/\
可以表示為以下列表:
這種表示有許多變體。 例如,當節點攜帶信息時,更容易將圖表示為到每個節點(而不僅僅是到葉子)的路徑列表。 因此,您可能需要調整此答案以解決您的特定問題。
這可以通過以深度優先的方式遍歷您的樹來建立。 相反,您可以遞歸地從路徑列表中重建您的樹。
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.