LeetCode 662. Maximum Width of Binary Tree in F#

URL

Maximum Width of Binary Tree - LeetCode

Code

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

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

let widthOfBinaryTree (root: Tree) : int =
    let rec widthOfBinaryTree' q ret =
        match q with
        | [] -> ret
        | (_, baseValue) :: _ ->
            let lastValue = List.last q |> snd

            let q' =
                q
                |> List.fold
                    (fun q (node, value) ->
                        match node with
                        | Leaf -> q
                        | Node(_, left, right) ->
                            match left, right with
                            | Leaf, Leaf -> q
                            | Node(_), Leaf ->
                                (left, value * 2 - baseValue) :: q
                            | Leaf, Node(_) ->
                                (right, value * 2 + 1 - baseValue) :: q
                            | Node(_), Node(_) ->
                                let leftValue = (value * 2) - baseValue
                                let rightValue = (value * 2 + 1) - baseValue
                                (right, rightValue) :: (left, leftValue) :: q)
                    [] |> List.rev

            let ret' = System.Math.Max(ret, lastValue - baseValue + 1)
            widthOfBinaryTree' q' ret'

    widthOfBinaryTree' [ (root, 0) ] 0