LeetCode 2415. Reverse Odd Levels of Binary Tree in F#

URL

https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/description/?envType=daily-question&envId=2024-12-20

Code

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

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

let toValue node =
    match node with
    | Leaf -> failwith "never reach here"
    | Node(v, _, _) -> v

let valsToTree (vals: int[] list) : Tree =
    let rec valsToTree' (vals: int[] list) len =
        match vals with
        | [] -> Array.init len (fun _ -> Leaf)
        | parents :: t ->
            let children = valsToTree' t (len * 2)

            parents
            |> Array.indexed
            |> Array.map (fun (i, v) -> Node(v, children.[2 * i], children.[2 * i + 1]))

    valsToTree' vals 1 |> Array.item 0

let reverseOddLevels (root: Tree) : Tree =
    let rec reverseOddLevels' q level =
        match q with
        | [] -> []
        | _ ->
            let vals = q |> List.map toValue |> List.toArray
            let vals = if level % 2 = 1 then Array.rev vals else vals

            let children =
                q
                |> List.fold
                    (fun acc node ->
                        match node with
                        | Leaf -> acc
                        | Node(_, Leaf, Leaf) -> acc
                        | Node(_, left, right) -> right :: left :: acc)
                    []
                |> List.rev

            vals :: reverseOddLevels' children (level + 1)

    let vals = reverseOddLevels' [ root ] 0
    valsToTree vals