LeetCode 114. Flatten Binary Tree to Linked List in F#

URL

leetcode.com/problems/flatten-binary-tree-t..

Code

github.com/syohex/dotnet-study/blob/master/..

type Tree =
    | Leaf
    | Node of int * Tree * Tree

let flatten (root: Tree) : Tree =
    let rec collectNodes node acc =
        match node with
        | Leaf -> acc |> List.rev
        | Node (v, left, right) ->
            (collectNodes left (v :: acc))
            @ (collectNodes right [])

    let rec nodesToFlattenTree nodes =
        match nodes with
        | [] -> Leaf
        | h :: t -> Node(h, Leaf, nodesToFlattenTree t)

    collectNodes root [] |> nodesToFlattenTree