To generate all (graphically-theoretical) subtrees of a given tree, I will need some auxiliary concepts.
A subtree is a connected subgraph of the pf tree or, equivalently, a subgraph that is also a tree.
, , . ( , ).
, , . () .
, .
.
data Tree a = Node a [Tree a] deriving Show
:
-- a descendant tree is either a tree itself,
-- or a descendant of a child of its root
descendants :: Tree a -> [Tree a]
descendants t@(Node a ts) = t : concatMap descendants ts
:
-- to get a rooted subtree, take a root, choose which children to
-- retain, take a rooted subtree of each retained child,
-- and attach the results to a copy of the root
rootedSubtrees :: Tree a -> [Tree a]
rootedSubtrees (Node a ts) = [Node a tts |
tts <- choices (map rootedSubtrees ts)]
-- this function receives a list of lists and generates all lists that
-- contain 0 or 1 element from each input list
-- for ex. choices ["ab", "cd"] = ["","c","d","a","ac","ad","b","bc","bd"]
choices :: [[a]] -> [[a]]
choices [] = [[]]
choices (xs:xxs) = cs ++ [x:c | x <- xs, c <- cs] where cs = choices xxs
,
subtrees :: Tree a -> [Tree a]
subtrees t = concatMap rootedSubtrees (descendants t)