LeetCode 2583. Kth Largest Sum in a Binary Tree in F#
URL
Kth Largest Sum in a Binary Tree - LeetCode
Code
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