Haskell:比较两个二叉树是否具有相同的元素

时间:2013-09-28 22:31:10

标签: haskell binary-tree

所以我正在开发一个函数来检测两个二叉树中是否有相同的数字。

所以我提出的是以下哪个工作得很好,但问题是我总共使用了5个函数。有没有另一种方法可以检测两个BT是否只有一个功能具有相同的元素?到目前为止,这是我的解决方案,似乎工作正常。

flatten :: BinTree a -> [a]
flatten Empty        = []
flatten (Node l x r) = flatten l ++ [x] ++ flatten r

splt :: Int -> [a] -> ([a], [a])
splt 0 xs = ([], xs)
splt _ [] = ([],[])
splt n (x:xs) = (\ys-> (x:fst ys, snd ys)) (splt (n-1) xs)

merge :: Ord a => [a] -> [a] -> [a] 
merge xs [] = xs
merge [] ys = ys    
merge (x:xs) (y:ys) = if (x > y) then y:merge (x:xs) ys else x:merge xs(y:ys)

msort :: Ord a => [a] -> [a]
msort [] =[]
msort (x:[]) = (x:[])
msort xs = (\y -> merge (msort (fst y)) (msort (snd y))) (splt (length xs `div` 2) xs)

areTreesEqual :: (Ord a) => BinTree a -> BinTree a-> Bool
areTreesEqual Empty Empty = True
areTreesEqual Empty a = False
areTreesEqual a Empty = False
areTreesEqual a b = msort (flatten (a) ) == msort (flatten (b))

1 个答案:

答案 0 :(得分:1)

怎么样

import Data.MultiSet as Set

equal a b = accum a == accum b
  where accum Empty = Set.empty
        accum (Node l x r) = Set.insert x (accum l `Set.union` accum r)

集合对于无序比较是可爱的,而多重集合将确保

 1   /=   1
1 1

例如,重复的数字被正确计算。如果这不是一个大问题,而不是MultiSet交换Set。我觉得3行对于这类事情是相当不错的。