calculating depth of a binary tree in Python

后端 未结 4 1424
春和景丽
春和景丽 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 16:09

    The error is coming from this line:

    return max(depth(self.left), depth(self.right)) + 1
    

    You're using depth as a function and trying to apply it to the left and right nodes. Because the left and right nodes are also nodes, they have the depth method.

    You should be calling the depth method like this:

    return max(self.left.depth(), self.right.depth()) + 1
    

    The self parameter is implicitly passed to the depth method, but using it with the dot operator tells Python that this method belongs to a Node instance, and it is not some other function not bound to an object.

提交回复
热议问题