我的問題是要求我在樹中返回節點的深度爲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,我不確定爲什麼
對不起,這是我的一個錯誤,我打算切換到正確的位置,但看起來像我複製了錯誤的代碼。我編輯它 –