【问题标题】:SML sum of binary tree二叉树的 SML 和
【发布时间】:2023-03-03 13:21:01
【问题描述】:
我必须编写一个函数来查找二叉树中所有元素的总和。
这就是它的定义(树):
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 是函数的名称。
感谢您的帮助。
【问题讨论】:
标签:
function
sum
binary-tree
sml
【解决方案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)依靠简单情况的解决方案。