DEV Community

Discussion on: Java Daily Coding Problem #008

Collapse
 
emlautarom1 profile image
Martín Emanuel

Thanks for sharing your solution! Quite an interesting challenge.

I tried to solve it using Haskell since I'm currently learning the language, and after a few mistakes I ended up with the following code:

data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show, Eq)

isUnival :: (Eq a) => Tree a -> Bool
isUnival tree = case tree of
  Empty -> False
  Node v l r -> case (l, r) of
    (Node lv _ _, Node rv _ _) -> v == lv && v == rv && isUnival l && isUnival r
    (Node lv _ _, Empty) -> v == lv && isUnival l
    (Empty, Node rv _ _) -> v == rv && isUnival r
    (Empty, Empty) -> True

univalCount :: (Eq a) => Tree a -> Int
univalCount tree = case tree of
  Empty -> 0
  Node _ l r -> if isUnival tree then 1 + childCount else childCount
    where
      childCount = univalCount l + univalCount r

As you can see, it's pretty short, and for me it looks very readable.
Have a nice day!

Collapse
 
awwsmm profile image
Andrew (he/him)

If there's one thing Java ain't, it's succinct. Great solution!