SOLUTION Thanks to Karolis Juodelė, here is my elegant solution to this problem! Thank you Karolis Juodelė :
prettyTree :: Show a=>BinTree a -> String
prettyTree Empty = ""
prettyTree (Node l x r) = prettyTree2((Node l x r),2)
prettyTree2 :: Show a=> (BinTree a, Int)-> String
prettyTree2 (Empty,_) = ""
prettyTree2 ((Node l x r),z) = prettyTree2(r,z+2) ++ replicate z ' ' ++ (show x) ++ ['\n'] ++ prettyTree2(l,z+2)
OLD So I am trying to print a binary tree like so:
putStr (prettyTree (Node (Node Empty 3 (Node Empty 7 Empty)) 8 (Node (Node Empty 8 Empty) 4 (Node Empty 3 Empty))))
3
4
8
8
7
3
What I have is the following which only prints them in two different lines:
data BinTree a = Empty | Node (BinTree a) a (BinTree a) deriving (Eq)
prettyTree :: Show a => BinTree a -> String
prettyTree Empty = ""
prettyTree (Node l x r) = prettyTree l ++ middle ++ prettyTree r
where
maxHeight = max (treeHeight l) (treeHeight r) + 1
middle = printSpace (maxHeight, maxHeight) ++ show x ++ "\n"
treeHeight :: BinTree a -> Integer
treeHeight Empty = 0
treeHeight (Node l x r) = 1 + max (treeHeight l) (treeHeight r)
printSpace :: (Integer,Integer) -> String
printSpace (0, _) = []
printSpace (_, 0) = []
printSpace (x, y) = " " ++ printSpace ((x `mod` y), y)
What I am trying to acomplish is that based on the total height of the tree, I will modulate the current height at the node, hence the root will be 0, then level 1 will be 1 and so fort.
I understand that I am actually passing the height twice for each level and I am not passing the total height of the tree. What can I do to actually get the total height of the tree for every level of the recursion?