Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 429. N-ary Tree Level Order Traversal in F#

Shohei Yoshida's photo
Shohei Yoshida
·Sep 5, 2022·

1 min read

URL

leetcode.com/problems/n-ary-tree-level-orde..

Code

github.com/syohex/dotnet-study/blob/master/..

type Tree =
    | Leaf
    | Node of int * (Tree list)

let levelOrder (root: Tree) : int list list =
    let rec levelOrder' nodes acc =
        match nodes with
        | [] -> acc |> List.rev
        | _ ->
            let vals, children =
                nodes
                |> List.fold
                    (fun (vals, children) node ->
                        match node with
                        | Leaf -> vals, children
                        | Node (v, cs) -> v :: vals, children @ cs)
                    ([], [])

            levelOrder' children ((vals |> List.rev) :: acc)

    levelOrder' [ root ] []
 
Share this