Skip to content

Instantly share code, notes, and snippets.

@imeckler
Last active October 12, 2017 01:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save imeckler/6053285 to your computer and use it in GitHub Desktop.
Save imeckler/6053285 to your computer and use it in GitHub Desktop.
BFS
{-# LANGUAGE LambdaCase #-}
import Control.Applicative
import Control.Monad.State
import System.Random
data Tree a = Empty | Bin a (Tree a) (Tree a)
deriving Show
-- O(n)
numAtDepths :: Tree a -> [Int]
numAtDepths = flip execState [] . go
where go Empty = return ()
go (Bin _ l r) = get >>= \case
[] -> go l >> go r >> modify (1:)
(x:xs) -> put xs >> go l >> go r >> modify (1 + x :)
-- O(n)
label :: Tree a -> Tree (Int, a)
label t = evalState (go (scanl (+) 0 ds) t) $ repeat 0
where ds = numAtDepths t
go _ Empty = return Empty
go (n:ns) (Bin x l r) = get >>= \(m:ms) ->
Bin (n + m + 1, x) <$> (put ms *> go ns l)
<*> go ns r
<* modify (m + 1 :)
randomTree = Bin () <$> subTree <*> subTree
where subTree = state random >>= \b -> if b then randomTree else return Empty
testT = Bin 'a'
(Bin 'b'
(Bin 'd'
Empty
(Bin 'h'
(Bin 'j' Empty Empty)
Empty))
(Bin 'e' Empty Empty))
(Bin 'c'
(Bin 'f'
Empty
(Bin 'i'
(Bin 'k' Empty Empty)
(Bin 'l' Empty Empty)))
(Bin 'g' Empty Empty))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment