LeetCode 1110. Delete Nodes And Return Forest in F#
URL
Delete Nodes And Return Forest - LeetCode
Code
type Tree =
| Leaf
| Node of int * Tree * Tree
let delNodes (root: Tree) (toDelete: int list) : Tree list =
let rec delNodes' node toDelete acc =
match node with
| Leaf -> Leaf, acc
| Node(v, left, right) ->
let left, acc = delNodes' left toDelete acc
let right, acc = delNodes' right toDelete acc
if Set.contains v toDelete then
let acc = if left = Leaf then acc else left :: acc
let acc = if right = Leaf then acc else right :: acc
Leaf, acc
else
Node(v, left, right), acc
let root, ret = delNodes' root (Set.ofList toDelete) []
if root = Leaf then ret else root :: ret