我正在尝试获得二叉搜索树的最大深度,但是我相信这棵树的计数是错误的。
我的代码:
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