LeetCode 2583. Kth Largest Sum in a Binary Tree in F#

URL

Kth Largest Sum in a Binary Tree - LeetCode

Code

https://github.com/syohex/dotnet-study/tree/master/fsharp/leetcode/challenge/202410/kth_largest_sum_in_a_binary_tree/main.fsx

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

let kthLongestLevelSum (root: Tree) (k: int) : int =
    let rec f node level acc =
        match node with
        | Leaf -> acc
        | Node(v, left, right) ->
            let sum = Map.tryFind level acc |> Option.defaultValue 0
            let acc = Map.add level (sum + v) acc
            let acc = f left (level + 1) acc
            f right (level + 1) acc

    f root 0 Map.empty
    |> Map.values
    |> Seq.sort
    |> Seq.rev
    |> Seq.tryItem (k - 1)
    |> Option.defaultValue -1