出于某种原因,我似乎无法让“查找”方法起作用。我认为这与范围界定问题有关...... root.val 似乎没有在全球范围内更新。我收到一条错误消息,说 AtributeError: 'int' object has no attribute 'val' 这是我目前的代码:
class BinaryNode:
def __init__(self, v):
self.val = v
self.leftChild = None
self.rightChild = None
def get(self):
return self.val
def set(self, v):
self.val = v
def getChildren(self):
children = []
if self.leftChild != None:
children.append(self.leftChild)
if self.rightChild != None:
children.append(self.rightChild)
return children
class Tree:
def __init__(self):
self.root = None
def setRoot(self, node):
self.root = node
def size(self):
if self.root == None:
return 0
def subtreeSize(node):
return 1 + sum(subtreeSize(c) for c in node.getChildren())
return subtreeSize(self.root)
class BinarySearchTree(Tree):
def insert(self, val):
self.insertNode(self.root, val)
def insertNode(self, node, val):
if node is None:
self.setRoot(BinaryNode(val))
elif val <= node.val:
node.leftChild = insertNode(BinaryNode(val), val)
elif val > node.val:
node.rightChild = insertNode(BinaryNode(val), val)
else:
node.val = val
def find(self, val):
self.findNode(self.root, val)
def findNode(self, node, val):
if node is None:
return False
elif val == node.val:
return True
elif val < node.val:
self.findNode(val, node.leftChild)
else:
self.findNode(val, node.rightChild)
if __name__ == "__main__":
btree = BinarySearchTree()
vals = [5]
for v in vals:
btree.insert(v)
tests = [8, 5]
for t in tests:
print "find(%i) = %s" % (t, ("True" if btree.find(t) else "False"))