Skip to content
Advertisement

TypeError while executing Binary tree code

I am getting an error while testing the following function. Can anybody help me with this?

code:

JavaScript

Here’s the test script:

JavaScript

And here’s the error I am getting:

JavaScript

Please let me know why is this happening?

Advertisement

Answer

As your largest_leaf_value will return None in its recursion base case, you need to be ready for lres or rres to get None assigned to them.

The type error occurs on the lines where you compare lres or rres with res, and tells you that a None value cannot be compared with res.

So you have two possibilities: either avoid that comparison from executing when lres or rres is None, or, don’t let your function return None, but instead return -infinity (since that value is smaller than all other finite numerical values).

Solution with the first approach:

JavaScript

Solution with the second approach:

JavaScript

Note that this will behave differently when you pass an empty tree (i.e. None) as argument in the initial call. Mathematically it is not defined what the maximum is in an empty collection, so it will depend on what you expect to happen in that case.

Finally, you can use max() to make the second version a bit shorter:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement