Function 二叉树的SML和
我必须写一个函数,它可以找到二叉树中所有元素的总和 这就是它的定义(树): 我不知道该怎么做。我承认我是SML的初学者 例如:Function 二叉树的SML和,function,sum,binary-tree,sml,Function,Sum,Binary Tree,Sml,我必须写一个函数,它可以找到二叉树中所有元素的总和 这就是它的定义(树): 我不知道该怎么做。我承认我是SML的初学者 例如:sumTree(节点(节点(叶1、3、叶2)、7、叶4))应该返回17。sumTree是函数的名称 谢谢你的帮助 我希望你能花点时间理解这一点。如果您对此有任何疑问,请告诉我: (* * This is a recursive datatype, because the Node constructor contains two * elements of type
sumTree(节点(节点(叶1、3、叶2)、7、叶4))
应该返回17。sumTree是函数的名称
谢谢你的帮助 我希望你能花点时间理解这一点。如果您对此有任何疑问,请告诉我:
(*
* 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
)中,则依赖于简单案例的解决方案
(*
* 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)