SML - 如何通过树的后序扫描创建列表
如何在 SML 中实现获取树并返回列表的函数。该列表由根据树的后序扫描的树节点中的值组成。
树数据类型
是:
datatype 'a Tree = Leaf | Branch of 'a * 'a Tree * 'a Tree;
How to implement a function in SML which gets a tree and returns a list. The list consists of the values in the tree nodes according to postorder scan of the tree.
The tree datatype
is:
datatype 'a Tree = Leaf | Branch of 'a * 'a Tree * 'a Tree;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可以简单地通过以下方式完成:
如果您有一个分支,首先访问它的左子树 (
createList(left)
),然后访问它的右子树 (createList(right)
),然后再访问它附加元素el
,所以基本上执行后序树遍历的操作。如果您想从Leaf
(空树)创建列表,结果将是一个空列表。That can be done simply by:
If you have a branch first visit it's left subtree (
createList(left)
), then it's right subtree (createList(right)
) and afterwards append the elementel
, so basically do what a postorder tree traversal does. If you want to create a list from aLeaf
(an empty tree) the result would be an empty list.更有效的解决方案:
这更有效,因为
@
必须完全展开其左侧参数才能将其添加到右侧参数,如果您重复将其应用于更长且更长时间的参数,这将变得非常昂贵更长的列表。相比之下,通过使用将子树的后序遍历前置到传入列表上的helper
函数,您只需构建整个列表一次。A more efficient solution:
This is more efficient because
@
has to completely unwind its left-hand argument to prepend it to the right-hand argument, which becomes very expensive if you are repeatedly applying it to longer and longer lists. By contrast, by using ahelper
function that prepends a subtree's postorder traversal onto a passed-in list, you can build the entire list just once.