简体   繁体   中英

flatten a tree with a list of subtrees in Haskell

I would like to flatten a tree which looks like this:

> data Tree a =  Leaf a
>              | Fork a [Tree a]
>              | Root [Tree a]

possible example:

Root [Fork 'a' [Fork 'b' [Leaf 'c'],Fork 'c' [Leaf 'b']],Fork 'b' [Fork 'a' [Leaf 'c'],Fork 'c' [Leaf 'a']],Fork 'c' [Fork 'a' [Leaf 'b'],Fork 'b' [Leaf 'a']]]

should become

["abc","acb","bac","bca","cab","cba"]

To explain why: I try to build kind of a permutation Tree. I wrote a function permute :: String -> Tree Char to visualize all possible permutations of an string into a Tree. But I dont get how to flatten this kind of tree. Thank you for help.

My approach here comes out to a depth first search.

data Tree a =  Leaf a          
            | Fork a [Tree a]       
            | Root [Tree a]         
            deriving(Show)

dfs :: Tree a -> [[a]]
dfs (Root ts) = concatMap dfs ts
dfs (Fork v ts) = map (v:) (concatMap dfs ts) 
dfs (Leaf v) = [[v]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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