let huff xs = let rec depth = function | Leaf _ -> 0 | Node (l,r) -> 1 + max (depth l) (depth r) let rec spojHloubku d = function | (d1,t1) :: (d2,t2) :: ts when d2=d -> (1+d2,Node (t1,t2)) :: spojHloubku d ts | (d1,t1) :: ts when d1=d -> (1+d1, t1) :: ts | ts -> ts let rec spojuj = function | [_, t] -> t | (_::(d, _)::_) as ts -> spojHloubku d ts |> spojuj xs |> List.map (fun t -> (depth t, t)) |> List.sortBy fst |> spojuj