BFS & DFS Documentation
BFS & DFS Documentation
Code:
data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show)
--Data type 'Tree' recursively
traverseDF :: Tree a -> [a]
--Function receives tree and
returns string
traverseDF Empty
= []
--If it receives empty, return
empty
traverseDF (Node a l r) = a : (traverseDF l) ++ (traverseDF r) -Recursive Concatenation
traverseBF :: Tree a -> [a]
--Function receives tree and
returns string
traverseBF tree = tbf [tree]
--Add the root node to the queue
list
where
tbf [] = []
tbf xs = map nodeValue xs ++ tbf (concat (map
leftAndRightNodes xs))
--adding nodes of a certain level then
calling tbf recursively again to add rest of levels
nodeValue (Node a _ _) = a
leftAndRightNodes (Node
right are empty return empty
leftAndRightNodes (Node
node is present return it
leftAndRightNodes (Node
node is present return it
leftAndRightNodes (Node
present return both
--Function that will create a
createTree = Node 'A'
(Node 'B'
(Node 'C'
(Node 'D'
)
(Node 'E'
(Node 'F'
(Node 'G'
(Node
Empty
))
)
_ Empty Empty) = []
_ Empty b)
= [b]
_ a Empty)
= [a]
_ a b)
tree
Empty Empty)
Empty Empty)
Empty Empty)
Empty (Node 'H'
'I' Empty Empty)
Documentation:
1. This code first initializes a tree recursively.
For Depth First Search:
2. A traversing function receives this tree and returns a
string for the Depth First Search.
3. If the tree is empty the return string is empty. If not, the
tree is represented by a tree with two nodes left and right.
4. Printing is done in a recursive behavior.
5. Sending the left tree and right tree and concatenating the
results together which will be the sequence of the output.
For Breadth First Search:
6. A function is called to traverse the tree for Breadth First
Search.
7. The root node is then added to a queue.
8. A function tbf is called and nodes of a certain level are
then added.
9. The function is then called recursively until all levels
have been printed out.
A function createTree is used to give values to the tree
we wish to use.