Hi I'm trying to rebuild a binary tree, I almost got it, except it throws me an error and I don't know why
buildTree :: (Ord a, Eq a) => [a] -> [a] -> Tree a
buildTree [] [] = Empty
buildTree preOrd inOrd = Node root left right
where root = head preOrd
left = buildTree leftPreOrd leftInOrd
right = buildTree rigthPreOrd leftInOrd
Just rootInd = elemIndex root inOrd
leftPreOrd = tail (take (rootInd + 1) preOrd)
rigthPreOrd = tail (drop rootInd preOrd)
leftInOrd = take rootInd inOrd
rightInord = drop (rootInd + 1) inOrd
When I call it using
buildTree [10,5,2,6,14,12,15] [2,5,6,10,12,14,15]
it throws me this:
Exception: reconstruir.hs:26:11-45: Irrefutable pattern failed for pattern Just rootInd
@chepner has spotted the error. If you'd like to know how to find and fix these sorts of errors yourself in the future, you may find the following answer helpful...
First, it helps to find the smallest test case possible. With a few tries, it's not hard to get your program to fail on a 2-node tree:
Now, try tracing the evaluation of
buildTree [5,2] [2,5]
by hand. If you evaluate this firstbuildTree
call manually, you'll find the variables involved have values:Everything looks fine, except
right
, which tries to build a tree with incompatible preorder and inorder lists. That's what causes the error, sincebuildTree [] [2]
tries to take thehead
of an empty list. (The error message is a little different for your test case, but the underlying cause is the same.)This pinpoints the problem as the second argument to
buildTree
in the definition ofright
-- the value2
shouldn't be included in the (empty) right tree. From there, it's easy to spot and fix the typo in the definition ofright
so it reads:After that fix, things seem to work okay.