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

URL

https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/?envType=daily-question&envId=2024-12-25

Code

https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/challenge/202412/find_largest_value_in_each_tree_row/main.fsx

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

let largestValues (root: Tree) : int list =
    let rec largestValues' q acc =
        match q with
        | [] -> List.rev acc
        | _ ->
            let q, maxVal =
                q
                |> List.fold
                    (fun (q, maxVal) node ->
                        match node with
                        | Leaf -> q, maxVal
                        | Node(v, Leaf, Leaf) -> q, max maxVal v
                        | Node(v, Leaf, right) -> right :: q, max maxVal v
                        | Node(v, left, Leaf) -> left :: q, max maxVal v
                        | Node(v, left, right) -> right :: left :: q, max maxVal v)
                    ([], System.Int32.MinValue)

            largestValues' q (maxVal :: acc)

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