Click here to Skip to main content
15,883,901 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Python
class Node:
    def __init__(self,mark,left,right):
        self.mark = mark
        self.left = left
        self.right = right

def height(tree:Node) -> int:
    if (tree is None):
        return -1
    else:
        return (max(height(tree.left),height(tree.right))+1)

tree = Node ('*', Node ('+', Node (6 , None , None ) ,
Node (5 , None , None )) ,
Node (1 , None , None ))


What I have tried:

to calculate the height of the tree of Nodes ... but dont know the why we should return -1 if tree is None
Posted
Updated 8-Sep-20 21:30pm

Seems these are not your codes and you are trying to figure what they mean. Assuming that, intent of whoever wrote this code would be to have some integer value to associate with no tree.

Problem statement is to calculate height of tree. If there is only root, you can define that as length 0 or 1.
if you define that as 0, -1 would make sense for non existent tree. If you plan to set length as 1 then you can also set this value as 0 for non existent tree.

It's more on what you want to define as for length.
 
Share this answer
 
So that max always finds higher values ...

If you aren't sure why something is the way it is, look at the code while it's running.
Fortunately, you have a tool available to you which will help you do that: the debugger. How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. You can then look at your variable contents while your code is running and follow exactly what it is doing by single-stepping each line in turn.
 
Share this answer
 
Quote:
Why we must return -1 if the tree is none ?

Probably because -1 is an impossible normal answer, just a guess.
It should be obvious that -1 is a special answer to handle a special case.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900