【发布时间】:2017-04-13 00:38:33
【问题描述】:
我想从一个整数列表[Int] -> [T] 中生成所有可能的树,但我只生成一棵树。
1 1
2 2
3 5
4 14
5 42
喜欢这些加泰罗尼亚数字。如果我的列表大小是 3,我想生成 5 棵可能的树,如果是 4 - 14 棵可能的树。
代码:
data T = N T T | L Int deriving (Show)
toT :: [Int] -> T
toT [] = L 0
toT [n] = L n
toT ns = T (toT (take mid ns)) (toT (drop (mid+1) ns))
where
mid = length ns div 2
例如:toT [1..3]
输出:N (L 1) (N (L 2) (L 3)) 和 N (N (L 1) (L 2)) (L 3)。
现在我是这样做的
toTree [] = error "!!"
toTree [n] = Leaf n
toTree ns = Node leftTree rightTree
where
leftTree = toTree $ take (length(ns)-1) ns
rightTree = toTree $ drop (length(ns)-1) ns` ı want ns length contiue descend one point recursive but ı didnt
我怎么能做到这一点?在递归中我将发送相同的列表但长度将下降我再次发送 [1,2,3] 大小 3 我发送 [1,2,3] 长度 2
【问题讨论】:
-
实际上有 n!*C(n-1) 棵不同的树,有 n 个叶子; C(n-1) 个形状,n!在叶子中放置 n 个整数的方法。
-
这也不像把你的列表分成两半那么简单;每个子树中有 k=1,...,n-1 个叶子的形状,而不仅仅是每个子树中的 n/2 个叶子。
-
@chepner 显示的可能树形状的数字对应于将值存储在节点中并具有空叶子的二叉树:
data Tree a = Branch a (Tree a) (Tree a) | Empty。 -
在您的示例中,您使用您的数据类型显示了 3 个整数的 2 种可能的树形,但之前您提到了 5(表格也显示了 5)。哪个是正确的,数据类型还是表格?
-
这样的桌子尺寸 1 树 1, 尺寸 2 树 1, 尺寸 3 树 2, 尺寸 4 树 5 尺寸 5 树 14 sory for msitake
标签: haskell tree enumeration template-haskell catalan