jmasterx
jmasterx

Reputation: 54193

Converting a BinaryTree to a Tree?

I have 2 classes: One which is a Tree which can have N subtrees, and BinaryTree can have at most 2 subtrees.

The classes are defined like so:

data Tree a = EmptyTree | Tree a [Tree a] deriving (Show, Ord, Eq)
data BinTree a = EmptyBin | Node a (BinTree a) (BinTree a) deriving (Show, Ord, Eq)

Is there a way I could convert a BinaryTree into a Tree?

Thanks

Upvotes: 1

Views: 109

Answers (1)

AndrewC
AndrewC

Reputation: 32475

Sure. The structure of the Tree allows us to put the two subtrees into the list:

convert EmptyBin = EmptyTree
convert (Node a l r) = Tree a [convert l,convert r]

If you wanted to convert the other way, that might be more complex, depending on how you wanted to branch a long list of subtrees, but you could use an Ord a context to help you there.

Upvotes: 5

Related Questions