二叉树的SML和
SML sum of binary tree
我必须编写一个函数来计算二叉树中所有元素的总和。
这就是它的定义(树):
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))
should return 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
)依赖简单情况下的解决方案。
我必须编写一个函数来计算二叉树中所有元素的总和。
这就是它的定义(树):
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))
should return 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
)依赖简单情况下的解决方案。