new: Solved problems 61 to 63

This commit is contained in:
Sayantan Santra 2025-02-24 21:57:08 -06:00
parent f88a69d1ac
commit 9a20c34c8e
Signed by: SinTan1729
GPG key ID: 0538DD402EA50898
5 changed files with 64 additions and 0 deletions

View file

@ -0,0 +1,8 @@
data Tree a = Empty | Branch a (Tree a) (Tree a)
deriving (Show, Eq)
countLeaves :: Tree a -> Int
countLeaves Empty = 0
countLeaves (Branch _ Empty Empty) = 1
countLeaves (Branch _ branch1 branch2) =
countLeaves branch1 + countLeaves branch2

View file

@ -0,0 +1,8 @@
data Tree a = Empty | Branch a (Tree a) (Tree a)
deriving (Show, Eq)
leaves :: Tree a -> [a]
leaves Empty = []
leaves (Branch a Empty Empty) = [a]
leaves (Branch _ branch1 branch2) =
leaves branch1 ++ leaves branch2

View file

@ -0,0 +1,8 @@
data Tree a = Empty | Branch a (Tree a) (Tree a)
deriving (Show, Eq)
internals :: Tree a -> [a]
internals Empty = []
internals (Branch _ Empty Empty) = []
internals (Branch a branch1 branch2) =
(a : internals branch1) ++ internals branch2

View file

@ -0,0 +1,8 @@
data Tree a = Empty | Branch a (Tree a) (Tree a)
deriving (Show, Eq)
atLevel :: Tree a -> Int -> [a]
atLevel Empty _ = []
atLevel (Branch a _ _) 1 = [a]
atLevel (Branch _ branch1 branch2) n =
atLevel branch1 (n - 1) ++ atLevel branch2 (n - 1)

View file

@ -0,0 +1,32 @@
data Tree a = Empty | Branch a (Tree a) (Tree a)
deriving (Show, Eq)
completeBinaryTreeNumbered :: Int -> Int -> Tree Int
completeBinaryTreeNumbered m n =
Branch m branch1 branch2
where
branch1 =
if 2 * m <= n
then completeBinaryTreeNumbered (2 * m) n
else Empty
branch2 =
if 2 * m + 1 <= n
then completeBinaryTreeNumbered (2 * m + 1) n
else Empty
useSameCharLabel :: Char -> Tree a -> Tree Char
useSameCharLabel _ Empty = Empty
useSameCharLabel c (Branch _ branch1 branch2) =
Branch c branch1' branch2'
where
branch1' = useSameCharLabel c branch1
branch2' = useSameCharLabel c branch2
completeBinaryTree :: Int -> Tree Char
completeBinaryTree n = useSameCharLabel 'x' $ completeBinaryTreeNumbered 1 n
isCompleteBinaryTree :: Tree a -> Bool
isCompleteBinaryTree Empty = True
isCompleteBinaryTree (Branch _ _ Empty) = True
isCompleteBinaryTree (Branch _ branch1 branch2) =
isCompleteBinaryTree branch1 && isCompleteBinaryTree branch2