问题描述
你好我想重建一个二叉树,我几乎得到它,只是它抛出一个错误,我不知道为什么
buildTree ::(Ord a,Eq a)=> [a] - > [a] - >树a
buildTree [] [] =空
buildTree preOrd inOrd =节点root左右
其中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
当我打电话给它使用
buildTree [10,5,2,6,14,12,15] [2,5,6 ,10,12,14,15]
它引发了我:
例外情况:reconstruir.hs:26:11-45:不可模仿的模式失败只需rootInd
运行时在这条线上失败:
只需rootInd = elemIndex root inOrd
elemI ndex
在运行示例输入时返回 Nothing
,但是您的代码表示它将始终返回 Just
,所以运行时崩溃。您需要处理 elemIndex root inOrd
返回 Nothing
。
也许更重要的是,您应该使用显示为编译器错误,以便您的代码无法编译以开始。
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:
Just rootInd = elemIndex root inOrd
elemIndex
is returning Nothing
when running your example input, but your code says it will always return a Just
, so the runtime crashes. You need to handle the case where elemIndex root inOrd
returns Nothing
.
Perhaps more importantly, you should enable all warnings with the -Wall
flag to show up as compiler errors so that your code wouldn't compile to begin with.
这篇关于从预订和中间列表重建二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!