Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 112. Path Sum in F#

Shohei Yoshida's photo
Shohei Yoshida
·Oct 4, 2022·

1 min read

URL

leetcode.com/problems/path-sum

Code

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

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

let hasPathSum (root: Tree) (targetSum: int) : bool =
    let rec hasPathSum' node sum targetSum =
        match node with
        | Leaf -> sum = targetSum
        | Node (v, left, right) ->
            hasPathSum' left (sum + v) targetSum
            || hasPathSum' right (sum + v) targetSum

    match root with
    | Leaf -> false
    | _ -> hasPathSum' root 0 targetSum
 
Share this