LeetCode 1038. Binary Search Tree to Greater Sum Tree in F#

URL

https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/description/?envType=daily-question&envId=2024-06-25

Code

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

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

let bstToGst (root: Tree) : Tree =
    let rec bstToGst' node sum =
        match node with
        | Leaf -> Leaf, sum
        | Node(v, left, right) ->
            let right', sumRight =
                match right with
                | Leaf -> right, sum
                | Node(_) -> bstToGst' right sum

            let sum = sumRight + v

            let left', sumLeft =
                match left with
                | Leaf -> left, sum
                | Node(_) -> bstToGst' left sum

            Node(sum, left', right'), sumLeft

    bstToGst' root 0 |> fst