Skip to content

Instantly share code, notes, and snippets.

@L-TChen
Last active November 30, 2018 16:06
Show Gist options
  • Save L-TChen/ef9ab8b4c5134de967bc741f892da75a to your computer and use it in GitHub Desktop.
Save L-TChen/ef9ab8b4c5134de967bc741f892da75a to your computer and use it in GitHub Desktop.
Chris Okasaki's Queue-Based Breadth-First Traversal and the Reconstruction from its Sequential Representation of Binary Tree
{-# LANGUAGE DeriveGeneric #-}
{- Building a tree based on its bfs result. -}
module BFS where
import Test.QuickCheck hiding ((><))
import GHC.Generics
import Generic.Random
import Data.Sequence (Seq (..), singleton, (><))
data Tree a = Leaf
| Node { left :: Tree a
, label :: a
, right :: Tree a}
deriving (Show, Read, Eq, Generic)
instance Arbitrary a => Arbitrary (Tree a) where
arbitrary = genericArbitraryRec uniform `withBaseCase` return Leaf
bfTrav :: Tree a -> Seq (Maybe a)
bfTrav t = bfTrav' $ singleton t
where
bfTrav' Empty = Empty
bfTrav' (Leaf :<| ts) = Nothing :<| bfTrav' ts
bfTrav' (Node l x r :<| ts) = Just x :<| bfTrav' (ts :|> l :|> r)
bfBuild :: Seq (Maybe a) -> Tree a
bfBuild ds | (t :<| Empty) <- bfBuild' ds = t
where
bfBuild' Empty = Empty
bfBuild' (Nothing :<| xs) = Leaf :<| bfBuild' xs
bfBuild' (Just x :<| xs) =
let (ts :|> l :|> r) = bfBuild' xs
in Node l x r :<| ts
prop t = t == bfBuild (bfTrav t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment