Last active
November 30, 2018 16:06
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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