我必须编写一个函数,它将找到二叉树中所有元素的总和。
这是如何定义的(树):
datatype 'a tree= Leaf of 'a | Node of 'a tree * 'a * 'a tree
我不知道该怎么做。我承认我是SML的初学者。
例如:sumTree (Node (Node (Leaf 1, 3, Leaf 2), 7, Leaf 4))
应返回17. sumTree是函数名称。
感谢您的帮助。
答案 0 :(得分:1)
我希望你花点时间了解这一点。如果您对此有任何疑问,请与我们联系:
(*
* This is a recursive datatype, because the Node constructor contains two
* elements of type `tree`, the type which we're currently defining.
*)
datatype 'a tree =
Leaf of 'a
| Node of 'a tree * 'a * 'a tree
(*
* Notice how the structure of the `sumTree` function follows the structure
* of the `tree` datatype. But `tree` is a recursive datatype, which means
* that `sumTree` will probably be a recursive function. This is called
* structural recursion. We recurse accordingly to the structure of the type.
*)
fun sumTree (Leaf n) = n
| sumTree (Node (left, n, right)) = (sumTree left) + n + (sumTree right)
基本思想是为简单案例(Leaf
)解决问题,在复杂案例中(Node
)依赖于简单案例的解决方案。