Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

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

Shohei Yoshida's photo
Shohei Yoshida
·Jul 27, 2022·

1 min read

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
 
Share this