1

I am trying to define a function which will return the list of all paths through a given binary tree. I have the following functions defined already:

data BTree a = Leaf a | Node a (BTree a) (BTree a)
     deriving (Show,Eq)

paths :: BTree a -> [[a]] 
paths (Leaf a) = [[]]
paths (Node x left right) = map (x:) (paths left ++ paths right)

With this function I have the following results for example: [[5,4],[5,4],[5,3],[5,3]] . But I was supposed to have as a result the output [[5,4,1],[5,4,2],[5,3,3],[5,3,4]]. Do anyone know why i dont get the 3rd value? Thank you

0

1 Answer 1

2

Your BTree type is:

data BTree a = Leaf a | Node a (BTree a) (BTree a)

Note that, unlike a list, it is never empty: both the leaves and the nodes contain values of type a. That being so, if you have a case in paths that always produces empty lists, such as...

paths (Leaf a) = [[]]

... you are necessarily throwing values away. What you want instead is:

paths :: BTree a -> [[a]] 
paths (Leaf a) = [[a]]
paths (Node x left right) = map (x:) (paths left ++ paths right)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.