calculating depth of a binary tree in Python

后端 未结 4 1423
春和景丽
春和景丽 2021-02-20 15:16

I am new to programming and am trying to calculate the depth of a binary tree in Python . I believe that my error is because depth is a method of the Node class and not a regula

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-20 15:49

    For clarity I would suggest writing your depth method like this:

    def depth(self):
        current_depth = 0
    
        if self.left:
            current_depth = max(current_depth, self.left.depth())
    
        if self.right:
            current_depth = max(current_depth, self.right.depth())
    
        return current_depth + 1
    

提交回复
热议问题