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
The runtime is failing on this line:
elemIndexis returningNothingwhen running your example input, but your code says it will always return aJust, so the runtime crashes. You need to handle the case whereelemIndex root inOrdreturnsNothing.Perhaps more importantly, you should enable all warnings with the
-Wallflag to show up as compiler errors so that your code wouldn't compile to begin with.