Python 为什么验证二叉树需要+;1和-1在最后阶段?
这是检查二叉树的有效解决方案:Python 为什么验证二叉树需要+;1和-1在最后阶段?,python,binary-tree,Python,Binary Tree,这是检查二叉树的有效解决方案: # Return true if the given tree is a BST and its values # >= min and <= max def isBSTUtil(node, mini, maxi): # An empty tree is BST if node is None: return True # False if this node violates min/max constra
# Return true if the given tree is a BST and its values
# >= min and <= max
def isBSTUtil(node, mini, maxi):
# An empty tree is BST
if node is None:
return True
# False if this node violates min/max constraint
if node.data < mini or node.data > maxi:
return False
# Otherwise check the subtrees recursively
# tightening the min or max constraint
return (isBSTUtil(node.left, mini, node.data -1) and
isBSTUtil(node.right, node.data+1, maxi))
这里我遗漏了什么?在BST中,节点的值不能同时出现在它的子树中。啊,这样就停止了重复?它呈现树
(3,a,nil);A=(3,无,无)
不是BST。如果这是您的意思,那么是的。如果将范围测试更改为node.data=maxi
,则可以删除+/-1。
isBST(4, -99999, 99999)
(ok, ok, ok)
isBST(2, -99999, 4)
(ok, ok, ok)
isBST(1, -99999, 2)
(ok, ok, ok)
True