[back]

Binary Tree to Rose Tree

type 'a tree
  = Empty
  | Node of 'a * 'a tree * 'a tree

type 'a rtree = Node of 'a * 'a rtree list

Implement the function

val rtree_of_tree : 'a tree -> 'a rtree option

so that rtree_of_tree t is None if t is empty and, otherwise, is Some t' where t' is a representation of t as a nonempty tree. In particular, each child of a Node that is Empty should simply not appear in the list of children of the corresponding Node.

Examples

let t1 : int tree =
  Node
    ( 1
    , Node (2, Empty, Empty)
    , Node (3, Empty, Node (4, Empty, Empty))
    )
let _ = assert (rtree_of_tree t1 =
                Some (Node (1, [Node (2, []); Node (3, [Node (4, [])])])))
let _ = assert (rtree_of_tree (Node (1, Empty, Empty)) = Some (Node (1, [])))
let _ = assert (rtree_of_tree Empty = None)