Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell traverse tree inorder preorder postorder

Tags:

haskell

tree

I have the following Haskell data definition:

data Tree = Leaf Int | Node Int Tree Tree deriving Show

and I wrote the following programs to traverse trees preorder, inorder and postorder:

preorder(Leaf n) = n
preorder(Node n t0 t1) = [n] ++ preorder t0 ++ preorder t1

inorder(Leaf n) = n
inorder(Node n t0 t1) = inorder t0 ++ [n] ++ inorder t1

postorder(Leaf n) = n
postorder(Node n t0 t1) = postorder t0 ++ postorder t1 ++ [n]

The error that I get is:

- Type error in application  
*** Expression     : preorder t0 ++ preorder t1  
*** Term           : preorder t1  
*** Type           : Int  
*** Does not match : [a]  

I need to return a list that contains all tree integers in appropriate order. Any help is highly appreciated as I am new to Haskell.

like image 519
Adriana Avatar asked Dec 12 '22 15:12

Adriana


1 Answers

You're returning Int from the base case but [Int] from the constructive case. The leaves should be lists too.

like image 55
geekosaur Avatar answered Dec 29 '22 19:12

geekosaur