Reputation: 129
I have just introduced myself to oop and binary trees in Python, but I ran into problems while I tried to implement the max depth method. It does not seem to give me the right answer, it gives me 1 whereas the number should be much bigger or perhaps I'm completely misunderstanding something. I added a fraction of my code below
class Node:
def __init__(self, value, left=None, right=None):
self.left = left
self.right = right
self.value = value
self.count = 1
def depth(self):
if self.left:
left_depth = self.left.depth()
else:
left_depth = 0
right_depth = self.right.depth() if self.right else 0
print(max(left_depth, right_depth) + 1)
tree = createTree(words) # list of words
tree.depth()
Upvotes: 0
Views: 1448
Reputation: 526683
print(max(left_depth, right_depth) + 1)
should be...
return max(left_depth, right_depth) + 1
so that your .depth()
method actually returns a value when called.
Then, at the end when you actually want a result:
print(tree.depth())
Also, it's a bit odd that you're using two different if-else constructs.
left_depth = self.left.depth() if self.left else 0
right_depth = self.right.depth() if self.right else 0
would work just fine and be more concise.
Upvotes: 2