Search for all n-ary tree subtrees

I am trying to find all the subtrees of an n-ary tree. Only BFS or DFS do not work. Because the tree is not binary. For example:

        1
     /    \
    2      3
   / \    /|\
  4   6  5 7 8
        / \
       9   10

I want to show all subtrees, including this one

        1
     /    \
    2      3
     \     |
      6    7

How can I extract this subtree from the original?

+4
source share
2 answers

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.

, , . ( , ).

, , . () .

, .

.

-- a (rooted) tree is a root node and a list of children attached to it
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)
+2

.

  • , . - ~ 2 ^ ( ). , 2 ^ ( ) ( , ), , , .
  • DFS.

- , 4, 5, 8.

, node.

0

Source: https://habr.com/ru/post/1611282/


All Articles