LeetCode 783. Minimum Distance Between BST Nodes in F#

URL

Minimum Distance Between BST Nodes - LeetCode

Code

https://github.com/syohex/dotnet-study/tree/master/fsharp/leetcode/problems/0783/main.fsx

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

let minDiffInBST (root: Tree) : int =
    let rec collectValues node acc =
        match node with
        | Leaf -> acc
        | Node(v, left, right) ->
            let acc' = collectValues left (v :: acc)
            collectValues right acc'

    collectValues root []
    |> List.sort
    |> List.pairwise
    |> List.fold (fun acc (v1, v2) -> System.Math.Min(acc, v2 - v1)) System.Int32.MaxValue