0

I would like to create a data type which represents a binary tree which has the values stored only in the leaves, then a function sub to check if a tree is subtree of other tree. Here is my code, but I got no idea how to implement the function 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 Answer 1

2

First, you need a function to see if two trees are equal. You can derive Eq or implement something recursively like this

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

With that you can do

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

The first tree is a sub-tree of the second if both are equal or it is a sub-tree of the left or the right sub-tree.

Sign up to request clarification or add additional context in comments.

1 Comment

Word of warning: This is probably quite inefficient. I'm not sure if there is a more efficient way or not.

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.