这是一个二叉树的类型。
问题在于,我对这段代码非常不满意——即便是对我来说,理解都非常困难。我的做法实际上是在每个层次上创建一个包含左右两边所有子树的列表(并确定子树是左儿子还是右儿子以确定形状),然后比较每个层级的列表。如果它们相同,则增加结果;否则,返回结果。
但是,使用这种“算法”时,我最终得到了这段复杂的代码。那么是否有更简单的方法可以实现呢?
type tree =
| Node of tree * int * tree
| Null;;
我有一个问题需要解决:
编写一个名为 tree -> tree -> int
的函数,该函数返回一个数字,表示从根节点开始向下多少层树的值和形状都是相同的。以下是我编写的解决方案:
let rec identical l1 l2 =
match (l1, l2) with
| ([], []) -> true
| ((tree1, s1) :: t1, (tree2, s2) :: t2) ->
if s1 = s2 then
match (tree1, tree2) with
| (Null, Null) -> identical t1 t2
| (_, Null) -> false
| (Null, _) -> false
| (Node (l1, x1, r1), Node (l2, x2, r2)) ->
if x1 = x2 then identical t1 t2
else false
else false;;
let unfold l =
let l = List.filter (fun (a, b) ->
if a = Null then false else true) l in
if List.length l = 0 then raise Nulls else
List.fold_left (fun acc (a, b) ->
match a with
| Node (l, x, r) ->
(l, "l") :: (r, "r") :: acc) [] l;;
let compare t1 t2 =
let rec aux l1 l2 result =
if (List.length l1 <> List.length l2)
then result
else
if (identical l1 l2) then
try
aux (unfold l1) (unfold l2) (result + 1)
with
| Nulls -> result
else
result
in aux [(t1, "r")] [(t2, "r")] 0;;
问题在于,我对这段代码非常不满意——即便是对我来说,理解都非常困难。我的做法实际上是在每个层次上创建一个包含左右两边所有子树的列表(并确定子树是左儿子还是右儿子以确定形状),然后比较每个层级的列表。如果它们相同,则增加结果;否则,返回结果。
但是,使用这种“算法”时,我最终得到了这段复杂的代码。那么是否有更简单的方法可以实现呢?