LeetCode 530. Minimum Absolute Difference in BST in F#

URL

Minimum Absolute Difference in BST - LeetCode

Code

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

open System

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

let getMinimumDifference (root: Tree) =
    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.windowed 2
    |> List.fold
        (fun acc w ->
            match w with
            | n1 :: n2 :: [] -> Math.Min(acc, Math.Abs(n1 - n2))
            | _ -> failwith "never reach here")
        Int32.MaxValue