I have a type tree defined as follows
type \'a tree = Leaf of \'a | Node of \'a * \'a tree * \'a tree ;;
I have a function to
There's a neat and generic solution using fold_tree and CPS - continuous passing style:
let fold_tree tree f acc =
let loop t cont =
match tree with
| Leaf -> cont acc
| Node (x, left, right) ->
loop left (fun lacc ->
loop right (fun racc ->
cont @@ f x lacc racc))
in loop tree (fun x -> x)
let depth tree = fold_tree tree (fun x dl dr -> 1 + (max dl dr)) 0