我必须为红黑树创建和完成功能。搜索功能特别令人头疼,因为它一直给我这个错误:
File "C:\Users\YOLO246\Desktop\2211 Assignment 2\Code\rbtree.py", line 135, in insert
(wasFound, node) = self.search(key)
TypeError: 'NoneType' object is not iterable
有人可以帮助我吗?
#!/bin/python
### Module that implements a Red-Black Tree
BLACK = 1
RED = 0
class RBTree:
class Node:
"""Nodes specific to this RBTree. Nodes point at trees and trees
point at nodes. This will allow rotations that change the
root.
"""
def __init__(self, parent, key, value, colour=RED, sentinel=None):
self._parent = parent
self._key = key
self._value = value
self._colour = colour
self._left = sentinel
self._right = sentinel
parent = property(fget=lambda self: self._parent,
doc="The node's parent")
@parent.setter
def set_parent(self, p):
self._parent = p
key = property(fget = lambda self: self._key,
doc="The node's key")
@key.setter
def set_key(self, k):
self._key = k
@property
def value(self):
"""The value associated with this node's key"""
return self._value
@value.setter
def set_value(self, v):
self._value = v
colour = property(fget=lambda self: self._colour,
doc="The node's colour, RED = 0, BLACK = 1")
@colour.setter
def set_colour(self, c):
self._colour = c
left = property(fget=lambda self: self._left,
doc="The node's left child")
@left.setter
def set_left(self, l):
self._left = l
right = property(fget=lambda self: self._right,
doc="The node's right child")
@right.setter
def set_right(self, r):
self._right = r
def __str__(self):
return ("<value: %s, colour: %s,%n parent: %s,%n left: %s,%n right: %s%n>" %
(self.key, self.colour,
self.parent, self.left, self.right))
## --- Start of RB-Tree methods ---
def __init__(self):
self._NIL = list()
self._root = self._NIL
NIL = property(fget=lambda self: self._NIL, doc="Constant sentinel NIL")
root = property(fget=lambda self: self._root, doc="The current root node")
@root.setter
def set_root(self, r):
self._root = r
def isRoot(self, node):
return self.root == node
def search(self, key):
"""Returns a tuple in the format (Found?, Node). The first part of
the tuple is True if the node was found and False
otherwise. The node component of the result is the node
containing key if it was already present, otherwise returns the
node that would be the parent of where key would have been
found in the tree. (This latter choice of returned node
avoids having to search the tree twice when inserting a new
key into the tree)
"""
parent = self.NIL
curr = self._root
while curr != self.NIL:
# Implement the rest of this loop body below
if key == curr.key:
return (True, curr)
elif key < curr.key:
parent=curr.left # code missing
curr=parent
else:
parent=curr.right # code missing
curr=parent
return (False, parent)