【问题标题】:How to produce an infinite binary tree? [closed]如何产生无限二叉树? [关闭]
【发布时间】:2019-05-09 16:18:18
【问题描述】:

我被要求为以下二叉树实现一个函数:

data BinaryTree a = Nil | BNode a (BinaryTree a) (BinaryTree a) 

我需要实现的函数应该产生一个完整的、对称的、无限的、a 的二叉树,并且应该有签名:

infTree :: a -> BinaryTree a

我该如何实现它?

【问题讨论】:

  • tr a = BNode a (tr a) (tr a).

标签: haskell tree binary-tree


【解决方案1】:

您可以创建一个循环引用,其中两个子节点都是父节点。

infTree :: a -> BinaryTree a
infTree x = tree
  where
    tree = BNode x tree tree

这与repeat函数的实现方式相同:

repeat :: a -> [a]
repeat x = xs where xs = x : xs

【讨论】:

  • 你能解释一下为什么这棵树是无限的吗?
  • @tal 如果你试图找到这棵树中的节点数,它会导致无限循环,因为它永远不会到达Nil
  • 由于值的自引用性质,它是一个无限树编码作为内存中的单个节点。
  • @tal 如果您以广度优先方式枚举infTree x 树的节点值,您将获得xs 的永无止境的列表。
  • 或:infTree x = fix (join (BNode x)),简化为infTree = fix . join . BNode
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
相关资源
最近更新 更多