data Tree t = Leaf | Node t (Tree t) (Tree t) deriving (Show) exT :: Tree Int exT = Node 1 (Node 2 (Node 4 Leaf Leaf) (Node 5 Leaf Leaf)) (Node 3 (Node 6 Leaf Leaf) (Node 7 Leaf Leaf)) bfsH :: Tree t -> [[t]] bfsH Leaf = [] bfsH (Node a l r) = [a]: (zipWithButKeepRest (++) (bfsH l) (bfsH r)) -- This version of zipWith simply returns the remainder of the non-empty list if one list is empty. THIS IS NOT THE USUAL DEFINITION! zipWithButKeepRest f [] x = x zipWithButKeepRest f x [] = x zipWithButKeepRest f (x:xs) (y:ys) = (f x y) : zipWithButKeepRest f xs ys foldTree :: b -> (t -> b -> b -> b) -> Tree t -> b foldTree fLeaf fNode = go where go Leaf = fLeaf go (Node a l r) = fNode a (go l) (go r) bfsByFold :: Tree t -> [[t]] bfsByFold = foldTree ([]) (\x l r -> [x]: (zipWithButKeepRest (++) l r))