Skip to content

Instantly share code, notes, and snippets.

@evgenii-malov
Last active February 23, 2022 20:13
Show Gist options
  • Select an option

  • Save evgenii-malov/eff4c42125f7ce7c4e4a456be60f29da to your computer and use it in GitHub Desktop.

Select an option

Save evgenii-malov/eff4c42125f7ce7c4e4a456be60f29da to your computer and use it in GitHub Desktop.
create balanced tree from sorted list
-- GHCi, version 8.8.4
{-# LANGUAGE ScopedTypeVariables #-}
import PrettyT -- https://www.youtube.com/watch?v=Ud-1Z0hBlB8&t=379s
import Data.List
import Data.Maybe
-- data Btree a = Empty | Node a (Btree a) (Btree a) deriving Show
-- build balanced binary search tree from sorted list
-- assume list is sorted
-- nodes must be uniq
-- https://www.youtube.com/watch?v=icRN-f408oE
b :: [a] -> Btree a
b [] = Empty
b l = Node m (b l_) (b r_) where
m = l !! mi
(l_,r) = splitAt mi l
r_ = tail r
mi = (length l) `div` 2
@evgenii-malov

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment