Skip to content

Instantly share code, notes, and snippets.

@guiocavalcanti
Created June 15, 2011 20:48
Show Gist options
  • Save guiocavalcanti/1028074 to your computer and use it in GitHub Desktop.
Save guiocavalcanti/1028074 to your computer and use it in GitHub Desktop.
data Tree t = EmptyTree
| Node t (Tree t) (Tree t)
deriving Show
nivel :: Float -> Int -> Int
nivel 0 _ = 0
nivel n x = if (n >= 2) then nivel (n / 2) (x + 1) else x
criarArvore :: Int -> Int -> Int -> Tree Int
criarArvore n _ 0 = EmptyTree
criarArvore n x y
| x > n = EmptyTree
| otherwise = Node x (criarArvore n (x*2) (y-1)) (criarArvore n ((x*2) + 1) (y-1))
criarArvoreCompleta :: Int -> Tree Int
criarArvoreCompleta 0 = EmptyTree
criarArvoreCompleta n = Node 1 (criarArvore n 2 (nivel (fromIntegral n) 0)) (criarArvore n 3 (nivel (fromIntegral n) 0))
balanceRaiz :: Tree Int -> Int
balanceRaiz EmptyTree = 0
balanceRaiz (Node t a b) = (valorPeso a) - (valorPeso b)
valorPeso :: Tree Int -> Int
valorPeso EmptyTree = 0
valorPeso (Node t a b) = mod ((mod t 113111) + (valorPeso a) + (valorPeso b)) 11311
main = do
putStrLn $ show $ criarArvoreCompleta 10
@md2perpe
Copy link

Tip: You could rewrite nivel to take just one argument and only Int (no Float):

nivel :: Int -> Int
nivel n = nivel' n 0
where
    nivel' 0 _ = 0
    nivel' 1 x = x
    nivel' n x = nivel' (n `div` 2) (x + 1)

criarArvoreCompleta :: Int -> Tree Int
criarArvoreCompleta 0 = EmptyTree
criarArvoreCompleta n = Node 1 (criarArvore n 2 (nivel n)) (criarArvore n 3 (nivel n))

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