Converting a BinaryTree to a Tree?

老子叫甜甜 提交于 2020-01-15 18:51:25

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/28511329/converting-a-binarytree-to-a-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!