tree - Level-order in Haskell -
i have structure tree , want print tree levels.
data tree = nd [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 levels? "levels tree" should print ["a", "bde", "cgflm", "hijkn", "o"]. think "iterate" suitable function purpose, cannot come solution how use it. me, please?
you need compute levels of subtrees , zip them after root:
levels :: tree [a] -> [[a]] levels (nd bs) = : foldr (zipwith' (++)) [] (map levels bs)
sadly, zipwith
doesn't right thing, can instead use:
zipwith' f xs [] = xs zipwith' f [] xs = xs zipwith' f (x:xs) (y:ys) = f x y : zipwith' f xs ys
update: there concern (which agree with) asked little weird it's not generic breadth-first tree list convertor. want concat result of:
levels' (nd bs) = [a] : foldr (zipwith' (++)) [] (map levels' bs)
Comments
Post a Comment