我试过差不多了,我通过了第一个测试用例而不是最后两个测试用例 这对大树的正确性和性能是错误的,它必须返回True或False。
import collections
class BinarySearchTree:
Node = collections.namedtuple('Node', ['left', 'right', 'value'])
@staticmethod
def contains(root, value):
if root.value == value:
return True
elif root.value < value:
return root.right.value == value #I am using == to return True or
#False
else:
return root.right.value == value
n1 = BinarySearchTree.Node(value=1, left=None, right=None)
n3 = BinarySearchTree.Node(value=3, left=None, right=None)
n2 = BinarySearchTree.Node(value=2, left=n1, right=n3)
print(BinarySearchTree.contains(n2, 3))
如何遍历元组中的元组内的元组?
答案 0 :(得分:1)
试试这段代码。
- 以前的代码是针对一个节点而不是整个树。
- else也检查了正确的节点而不是左边的节点。
醇>
import collections
class BinarySearchTree:
Node = collections.namedtuple('Node', ['left', 'right', 'value'])
@staticmethod
def contains(root, value):
if root.value == value:
return True
elif root.value < value:
if root.right == None:
return False
else:
return BinarySearchTree.contains(root.right,value)
#root.right.value == value #I am using == to return True or
#False
else:
if root.left == None:
return False
else:
return BinarySearchTree.contains(root.left,value)
#root.right.value == value
n4 = BinarySearchTree.Node(value=4, left=None, right=None)
n0 = BinarySearchTree.Node(value=0, left=None, right=None)
n1 = BinarySearchTree.Node(value=1, left=n0, right=None)
n3 = BinarySearchTree.Node(value=3, left=None, right=n4)
n2 = BinarySearchTree.Node(value=2, left=n1, right=n3)
print(BinarySearchTree.contains(n2, 14))