Tree 如何在SML中将树转换为O(n)时间复杂度的列表?
列表需要是顺序遍历。以下是我目前掌握的情况:Tree 如何在SML中将树转换为O(n)时间复杂度的列表?,tree,time-complexity,sml,Tree,Time Complexity,Sml,列表需要是顺序遍历。以下是我目前掌握的情况: datatype tree = Empty | Node of (tree * int * tree) fun combine (t1 : tree, t2 : tree) : tree = case t1 of Empty => t2 | Node(l1,x1,r1) => Node(combine(l1,r1),x1,t2) fun TTL (t : tree) : int list =
datatype tree =
Empty
| Node of (tree * int * tree)
fun combine (t1 : tree, t2 : tree) : tree =
case t1 of
Empty => t2
| Node(l1,x1,r1) => Node(combine(l1,r1),x1,t2)
fun TTL (t : tree) : int list =
let val tree = combine(t, Empty) in
case tree of
Empty => []
| Node(l, x, r) => x :: TTL(l)
end
这并没有以正确的顺序输出列表,我现在被卡住了。请提供帮助。遍历右子树,然后将节点的值附加到该列表,然后遍历左子树,同时向第二个列表添加元素。
您可以使用一个接受累加参数的辅助函数来执行此操作
fun TTL t =
let fun TTL' Empty ns = ns
| TTL' (Node(l, x, r)) ns = TTL' l (x::TTL' r ns)
in
TTL' t []
end
@molbdnilo发布的答案是有效的,但另一个建议的格式不适合作为评论。利用SML的模式匹配功能、类型推断和泛型类型 您有一个联合收割机功能:
fun combine (t1 : tree, t2 : tree) : tree =
case t1 of
Empty => t2
| Node(l1,x1,r1) => Node(combine(l1,r1),x1,t2)
让我们先去掉不必要的类型注释:
fun combine (t1, t2) =
case t1 of
Empty => t2
| Node(l1,x1,r1) => Node(combine(l1,r1),x1,t2)
现在,案例。。。of
也不是必需的,因为在这种情况下,我们可以直接在函数的参数列表中进行模式匹配
fun combine (Empty, t2) = t2
| combine (Node(l1, x1, r1), t2) = Node(combine(l1,r1),x1,t2)
最后,没有理由您的树
类型只需要处理int
datatype 'a tree = Empty | Node of ('a tree * 'a * 'a tree)
希望随着您对学习的深入,这些技巧中的一些能够帮助您的代码更容易推理,更灵活