Level-order in Haskell

Posted by brain_damage on Stack Overflow See other posts from Stack Overflow or by brain_damage
Published on 2010-04-28T18:34:59Z Indexed on 2010/04/28 18:37 UTC
Read the original article Hit count: 404

Filed under:
|
|
|
|

I have a structure for a tree and I want to print the tree by levels.

data Tree a = Nd a [Tree a] deriving Show
type Nd = String
tree = Nd "a" [Nd "b" [Nd "c" [], Nd "g" [Nd "h" [], Nd "i" [], Nd "j" [], Nd "k" []]], Nd "d" [Nd "f" []], Nd "e" [Nd "l" [Nd "n" [Nd "o" []]], Nd "m" []]]
preorder (Nd x ts) = x : concatMap preorder ts
postorder (Nd x ts) = (concatMap postorder ts) ++ [x]

But how to do it by levels? "levels tree" should print ["a", "bde", "cgflm", "hijkn", "o"]. I think that "iterate" would be suitable function for the purpose, but I cannot come up with a solution how to use it. Would you help me, please?

© Stack Overflow or respective owner

Related posts about haskell

Related posts about tree