简体   繁体   English

生成大小为n的所有二叉树

[英]generate all binary trees with size n

I'd like to write a function which returns all possible binary trees for any given size. 我想编写一个函数,该函数返回任何给定大小的所有可能的二叉树。

Unfortunately I have no clue, why my solution always returns an empty list, except for size 1. 不幸的是,我不知道为什么我的解决方案总是返回一个空列表(大小1除外)。

allTreesN :: Int -> t -> [Tree t]
allTreesN n t 
    | n == 0 = [ Leaf ]
    | otherwise = [(Node x t y) | i <- [0..n-1], x <- (allTreesN i t),y <- (allTreesN i t), size (Node x t y) == n]

You basically generate all trees of size i both for x and y , and then aim to construct a tree of size n . 您基本上会生成所有大小为ixy的树,然后旨在构造大小为n的树。 This will only work if i = 2 *n . 这仅在i = 2 *n But now a second problem occurs: we can never generate a tree of size 1 here, since 1 can not be divided by two. 但是现在出现了第二个问题:由于1不能被二除,因此我们永远无法在此处生成大小为1的树。 Since we can not generate a tree of size 1 , we thus can not generate trees of size 2 , and so on. 由于我们无法生成大小为1的树,因此无法生成大小为2树,依此类推。

We thus need to make sure we generate trees of the correct size. 因此,我们需要确保生成的树大小正确。 We can do that by generating a tree of size i , and another one of size ni-1 . 我们可以通过生成大小为i的树和大小为ni-1另一棵树来做到这一点。 If we construct a node of that size, we know for sure that the size of a node carrying these subtrees has size n , so we can even omit the check. 如果我们构造一个具有该大小的节点,则可以肯定地知道承载这些子树的节点的大小为n ,因此我们甚至可以省略检查。

So a correct implementation is: 因此,正确的实现是:

allTreesN :: Int -> a -> [Tree a]
allTreesN 0 _ = [Leaf]
allTreesN n v = [Node l v r | i <- [0..n-1],
                              l <- allTreesN i v,
                              r <- allTreesN (n-1-i) v]

For example: 例如:

Prelude> allTreesN 0 'a'
[Leaf]
Prelude> allTreesN 1 'a'
[Node Leaf 'a' Leaf]
Prelude> allTreesN 2 'a'
[Node Leaf 'a' (Node Leaf 'a' Leaf),Node (Node Leaf 'a' Leaf) 'a' Leaf]
Prelude> allTreesN 3 'a'
[Node Leaf 'a' (Node Leaf 'a' (Node Leaf 'a' Leaf)),Node Leaf 'a' (Node (Node Leaf 'a' Leaf) 'a' Leaf),Node (Node Leaf 'a' Leaf) 'a' (Node Leaf 'a' Leaf),Node (Node Leaf 'a' (Node Leaf 'a' Leaf)) 'a' Leaf,Node (Node (Node Leaf 'a' Leaf) 'a' Leaf) 'a' Leaf]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM