Haskell二叉树仅在叶子中具有值

时间:2016-04-17 22:12:19

标签: haskell binary-tree

我想创建一个数据类型,它表示一个二叉树,其值只存储在叶子中,然后是一个函数sub来检查树是否是其他树的子树。 这是我的代码,但我不知道如何实现函数sub

data BinaryTree a = Leaf a | Node (BinaryTree a) (BinaryTree a)  deriving Show

makeBinTree :: [a] -> BinaryTree a
makeBinTree lst = head $ mrg leaves
where
  leaves = map (\x -> Leaf x) lst
  mrg [] = []
  mrg [x] = [x]
  mrg (x:y:xs) = mrg ( (Node x y) : mrg xs)

sub :: Eq a => BinaryTree a -> BinaryTree a -> Bool

1 个答案:

答案 0 :(得分:2)

首先,您需要一个函数来查看两棵树是否相等。你可以派生Eq或像这样递归地实现一些东西

eq :: Eq a => BinaryTree a -> BinaryTree a -> Bool
eq (Leaf x) (Leaf y) = x == y
eq (Node l1 r1) (Node l2 r2) = (l1 `eq` l2) && (r1 `eq` r2)
eq _ _ = False

你可以这样做

sub :: Eq a => BinaryTree a -> BinaryTree a -> Bool
sub s (Leaf y) = s `eq` Leaf y
sub s t@(Node l r) = s `eq` t || sub s l || sub s r

如果两者都相等,则第一棵树是第二棵树的子树,或者它是左子树或右子树的子树。

相关问题