[英]SML sum of binary tree
I have to write a function which will find a sum of all elements in the binary tree. 我必须编写一个函数,它将找到二叉树中所有元素的总和。
Thats how it is defined (tree): 这是如何定义的(树):
datatype 'a tree= Leaf of 'a | Node of 'a tree * 'a * 'a tree
And I have no idea how should I do it. 我不知道该怎么做。 I admit that I am beginner with SML.
我承认我是SML的初学者。
For example: sumTree (Node (Node (Leaf 1, 3, Leaf 2), 7, Leaf 4))
should return 17. sumTree is name of function. 例如:
sumTree (Node (Node (Leaf 1, 3, Leaf 2), 7, Leaf 4))
应该返回17. sumTree是函数的名称。
Thanks for help. 感谢帮助。
I hope you'll take the time to understand this. 我希望你花时间去理解这一点。 Let me know if you have any questions regarding it:
如果您对此有任何疑问,请与我们联系:
(*
* 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)
The basic idea is to solve the problem for the easy case ( Leaf
) and in the complex case ( Node
) rely on the solution for the easy case. 基本思路是为简易案例(
Leaf
)解决问题,在复杂案例( Node
)中依赖解决方案来实现简单案例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.