LeetCode 988. Smallest String Starting From Leaf in F#
URL
Smallest String Starting From Leaf - LeetCode
Code
type Tree =
| Leaf
| Node of int * Tree * Tree
let smallestFromLeaf (root: Tree) : string =
let rec smallestFromLeaf' node acc ret =
match node with
| Leaf -> ret
| Node(v, left, right) ->
let acc' = v :: acc
if left = Leaf && right = Leaf then
match ret with
| [] -> acc'
| _ -> if acc' < ret then acc' else ret
else
let ret = smallestFromLeaf' left acc' ret
smallestFromLeaf' right acc' ret
smallestFromLeaf' root [] []
|> List.map (fun i -> i + int 'a' |> char)
|> System.String.Concat