99 questions/Solutions/72

From HaskellWiki
Jump to: navigation, search

(*) Construct the bottom-up order sequence of the tree nodes.

Write a predicate bottom_up(Tree,Seq) which constructs the bottom-up sequence of the nodes of the multiway tree Tree.

bottom_up :: Tree a -> [a]
bottom_up (Node x ts) = concatMap bottom_up ts ++ [x]

A more efficient version using an accumulator:

bottom_up :: Tree a -> [a]
bottom_up t = bottom_up_aux t []
  where bottom_up_aux :: Tree a -> [a] -> [a]
        bottom_up_aux (Node x ts) xs = foldr bottom_up_aux (x:xs) ts