I am trying to find the total depth of a BST in python(such that the root is at depth 1, its children depth 2, those children depth 3 etc) and the total is all of those depths added together. Ive been trying for about 5 hours straight now and cannot figure it out. Here is the code I have produced so far
class BinaryTreeVertex:
'''vertex controls for the BST'''
def __init__(self, value):
self.right = None
self.left = None
self.value = value
...
def total_Depth(self):
print ("val:", self.value)
if self.left and self.right:
return (self.left.total_Depth()) + 1 and (self.right.total_Depth()) + 1
elif self.left:
return 1 + self.left.total_Depth()
elif self.right:
return 1 + self.right.total_Depth()
else:
return 1
...
tree = BinarySearchTree()
arr = [6,10,20,8,3]
for i in arr:
tree.insert(i)
tree.searchPath(20)
print (tree.total_Depth()) #this calls the total_depth from vertex class
The generated tree then looks like this.
6 # Depth 1
___|___
3 10 # Depth 2
___|__
8 20 # Depth 3
But when I run it it prints:
val: 6
val: 3
val: 10
val: 8
val: 20
3
The 3 should actually be an 11 with this tree but I cannot figure out how to get it. Please help
edit: To clarify, i am NOT looking for the max depth, I know how to find this. I need the total depth the way i explained, where the depth is the level of the tree. it would be 11 here as 6 would have depth 1, 3 and 10 depth 2, and 8 and 20 depth 3, where 1+2+2+3+3=11. I need it for a ratio regarding run times
return (self.left.total_Depth()) + 1 and (self.right.total_Depth()) + 1? This is always going to return the depth of the right branch plus one. You probably wantmax((self.left.total_Depth()) + 1, (self.right.total_Depth()) + 1)expr1 and expr2. Olivier's answer shows the clean way of implementing your depth function in three lines.