Solved Binary Trees Problems
The definition of the trees is given by:
data Tree a = Node a (Tree a) (Tree a) | Empty
deriving (Show)
That is, a tree with elements of type a is, either an empty tree, either a node with an element (of type a) and two other trees of the same type. The deriving (Show) statement simply enables a visualization of trees.
Problem 1
Write a function size :: Tree a -> Int that, given a tree, returns its size, that is, the number of nodes it contains.
Input
let t7 = Node 7 Empty Empty
let t6 = Node 6 Empty Empty
let t5 = Node 5 Empty Empty
let t4 = Node 4 Empty Empty
let t3 = Node 3 t6 t7
let t2 = Node 2 t4 t5
let t1 = Node 1 t2 t3
size t1
Output : 7
data Tree a = Node a (Tree a) (Tree a) | Empty
deriving (Show)
size :: Tree a -> Int
size Empty = 0 -- Base Case: Empty Tree
size (Node _ lc rc) = 1 + size lc + size rc