0

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

所以我想出的是以下,它工作得很好,但问题是我总共使用了 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))
4

1 回答 1

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 行对于这类事情来说是相当不错的。

于 2013-09-28T22:38:50.720 回答