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
def depth(self):
if self.left == None and self.right == None:
return 1
return max(depth(self.left), depth(self.right)) + 1
should be
def depth(self):
return max(self.left.depth() if self.left else 0, self.right.depth() if self.right else 0) + 1
A more readable version:
def depth(self):
left_depth = self.left.depth() if self.left else 0
right_depth = self.right.depth() if self.right else 0
return max(left_depth, right_depth) + 1
The issue is that there is no function depth
. It's a method of the Node
object, so you would need to call it from the object itself (left and right). I shortened the code to self.left.depth() if self.left else 0
and self.right.depth() if self.right else 0
in order to remove the checks you previously have (they're implicit now) since I believe it is entirely possible that the left is None
while the right is a Node
or vice versa, which would cause the original code to throw an AttributeError
since None
does not have a method depth
.
Edit
In response to the question about the
block:
The line gives
if
is true-y (treated as true), and
if
is false-y (treated as false)