Shohei Yoshida
Shohei Yoshida's Blog

Follow

Shohei Yoshida's Blog

Follow

LeetCode 872. Leaf-Similar Trees in F#

Shohei Yoshida's photo
Shohei Yoshida
·Dec 8, 2022·

1 min read

URL

leetcode.com/problems/leaf-similar-trees

Code

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

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

let leafSimilar (root1: Tree) (root2: Tree) : bool =
    let rec collectLeaves node acc =
        match node with
        | Leaf -> acc
        | Node(v, Leaf, Leaf) -> v :: acc
        | Node(_, left, right) ->
            let acc' = collectLeaves left acc
            collectLeaves right acc'

    let leaves1 = collectLeaves root1 [] |> List.rev
    let leaves2 = collectLeaves root2 [] |> List.rev

    leaves1 = leaves2
 
Share this