我的问题是要求我在树中返回节点的深度为value
。返回值为二值搜索树的特定节点的深度
例如,如果我这样做depth(root, 7, 0 [depth initially])
,它应该返回2.
我的第一次尝试,我做了这样的事情
# value is the value wanted, count measures the 'depth'
def depth(root, value, count):
# if we are not at a empty node
if root != None:
# if we found our data, then just return the count (depth)
if root.data == value:
return count
# otherwise increase count, and traverse both sides
else:
count += 1
count = depth(root.left, value, count)
count = depth(root.right, value, count)
return count
当我运行这虽然我得到深度= 6,我不确定为什么
对不起,这是我的一个错误,我打算切换到正确的位置,但看起来像我复制了错误的代码。我编辑它 –