2013-09-28 37 views
0

因此,我正在研究一个函数,该函数检测两个二叉树是否具有相同的数字。Haskell:比较两个二叉树是否具有相同的元素

所以我想到的是以下工作正常,但问题是,我使用总共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)) 
+0

为什么你需要定义自己的合并排序函数,而不是使用'Data.List.sort'('By')?这将节省3个功能。 – kennytm

回答

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 

例如,重复的数字是正确计算。如果这不是一个大问题,那么换用代替Set。我认为3线对于这类事情是相当不错的。

相关问题