LeetCode 515. Find Largest Value in Each Tree Row in F#

URL

Find Largest Value in Each Tree Row - LeetCode

Code

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

open System

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

let largestValues (root: TreeNode) : int list =
    let rec largestValues' q acc =
        match q with
        | [] -> List.rev acc
        | _ ->
            let q', max =
                q
                |> List.fold
                    (fun (q, max) node ->
                        match node with
                        | Leaf -> failwith "never reach here"
                        | Node(v, left, right) ->
                            let max' = Math.Max(max, v)

                            match left, right with
                            | Leaf, Leaf -> q, max'
                            | Leaf, Node(_) -> right :: q, max'
                            | Node(_), Leaf -> left :: q, max'
                            | _, _ -> left :: right :: q, max')
                    ([], Int32.MinValue)

            largestValues' q' (max :: acc)

    match root with
    | Leaf -> []
    | _ -> largestValues' [ root ] []