Rebuild a binary tree from preorder and inorder lists

亡梦爱人 提交于 2019-12-02 06:44:25

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.

@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:

> buildTree [5,2] [2,5]
Node 5 (Node 2 Empty Empty) (Node *** Exception: Prelude.head: empty list

Now, try tracing the evaluation of buildTree [5,2] [2,5] by hand. If you evaluate this first buildTree call manually, you'll find the variables involved have values:

preOrd = [5,2]
inOrd = [2,5]
Just rootInd = Just 1

leftPreord = tail (take 2 [5,2]) = [2]
rightPreord = tail (drop 1 [5,2]) = []

leftInOrd = take 1 [2,5] = [2]
rigthInord = drop 2 [2,5] = []

root = 5
left = buildTree [2] [2]
right = buildTree [] [2]

Everything looks fine, except right, which tries to build a tree with incompatible preorder and inorder lists. That's what causes the error, since buildTree [] [2] tries to take the head 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 of right -- the value 2 shouldn't be included in the (empty) right tree. From there, it's easy to spot and fix the typo in the definition of right so it reads:

read = buildTree rigthPreOrd rightInOrd

After that fix, things seem to work okay.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!