I am given this type definition:
data Tree = Leaf Char | Branch2 Char Tree Tree | Branch3 Char Tree Tree Tree
How can I write a method that gives me the maximum path length of the tree (count the nodes in the path)?
I am given this type definition:
data Tree = Leaf Char | Branch2 Char Tree Tree | Branch3 Char Tree Tree Tree
How can I write a method that gives me the maximum path length of the tree (count the nodes in the path)?
You would want to write a recursive function to do this. For each Tree
constructor, you'll need a different case in your function. To start with, you know that the depth of any Leaf
is 1
, so
maxDepth :: Tree -> Int
maxDepth (Leaf _) = 1
maxDepth (Branch2 c left right) = maximum [???]
maxDepth (Branch3 c left center right) = maximum [???]
I'll let you finish the rest of the function. You could do it a few different ways as well (such as using max
instead of maximum
).
with lazy corecursive breadth-first tree traversal:
treedepth tree = fst $ last queue
where
queue = (1,tree) : gen 1 queue
gen 0 p = []
gen len ((d,Leaf _ ) : p) = gen (len - 1) p
gen len ((d,Branch2 _ l r) : p) = (d+1,l) : (d+1,r) : gen (len + 1) p
gen len ((d,Branch3 _ l c r) : p) = (d+1,l) : (d+1,c) : (d+1,r) : gen (len + ??) p
changing it to the depth-first traversal will turn it into a regular recursion.
I'd probably write a tail-recursive solution by using continuation passing.
depth :: Tree -> Int
depth t = go t id
where
go (Leaf _) k = k 0
go (Branch2 _ l r) k = go l $ \dl -> go r $ \dr -> k (1 + max dl dr)
go (Branch3 _ l m r) k = go l $ \dl -> go m $ \dm -> go r $ \dr -> k (1 + max dl (max dm dr))
depth :: Tree -> Int
depth (Leaf _) = 1
depth (Branch2 c left right) = max((depth(left) + 1) (depth(right) + 1))
depth (Branch3 c left center right) = max(max((depth(left) + 1) (depth(right) + 1)) (depth(center) + 1))
Is that right? Sorry i'm not so good in recursive programming.