我想獲得二叉搜索樹的最大深度,但是我相信樹計算錯誤。在二叉搜索樹中打印最大深度
我的代碼:
def BST_maxdepth(root):
curdepth = [1]
maxdepth = [1]
if root is None:
return -1
else:
curdepth[0] = 1
maxdepth[0] = 1
if root.left is not None or root.right is not None:
curdepth[0] += 1
if curdepth[0] > maxdepth[0]:
maxdepth[0] = curdepth[0]
BST_maxdepth(root.left)
BST_maxdepth(root.right)
return maxdepth[0]
類& BST:
class Node:
def __init__(self,value):
self.right = None
self.left = None
self.value = value
def BST_Insert(root, node): # root --> root of tree or subtree!
if root.value is None:
root = node # beginning of tree
else:
if root.value > node.value: # go to left
if root.left is None:
root.left = node
else:
BST_Insert(root.left, node)
if root.value < node.value: # go to right
if root.right is None:
root.right = node
else:
BST_Insert(root.right, node)
測試:
r = Node(8)
a = Node(5)
b = Node(2)
c = Node(1)
d = Node(3)
e = Node(7)
輸出:
2
預期輸出:
4
是不是你的深度實際上應該是4? – Michael
對不起,我使用了錯誤的樣本數據,我正在測試,但在這種情況下,你是對的 – Liondancer