我試圖實現一個二進制搜索樹類。我有兩堂課; BSTNode
和BST
。我試圖強制執行的制定者搜索樹屬性left
和right
:在Python中與遞歸和屬性設置器混淆
class BSTNode(object):
def __init__(self,new):
if type(new) is BSTNode:
self._data = new.data
else:
self._data = new
self._left = None
self._right = None
@property
def data(self):
return self._data
@property
def left(self):
return self._left
@left.setter
def left(self,data):
if data is None:
self._left = None
else:
n = BSTNode(data)
if n.data >= self.data:
del n
raise ValueError("Value must be less-than parent!")
self._left = n
@property
def right(self):
return self._right
@right.setter
def right(self,data):
if data is None:
self._right = None
else:
n = BSTNode(data)
if n.data < self.data:
del n
raise ValueError("Value must be greater-than or equal-to parent!")
self._right = n
class BST(object):
def __init__(self):
self._root = None
@property
def root(self):
return self._root
@root.setter
def root(self,value):
self._root = BSTNode(value)
def binary_insert(self,list_in):
self.root = binary_insert(list_in,0,len(list_in) - 1)
現在,我想實現的方法binary_insert(self,list_in)
,我插入排序列表到樹這樣的樹是平衡的(使用基本上是二分搜索);然而,斷root
我的左和右節點始終None
,雖然我在函數中明確指定他們,我相信我的指標是正確的,因爲我得到了下面的打印,當我運行它:
> t = BST()
> list_in = [0,1,2,3,4,5,6,7,8]
> t.binary_insert(list_in)
4
1
0
2
3
6
5
7
8
這裏是我的功能(注意實例方法binary_insert
上述BST
類):
def binary_insert(list_in,imin,imax):
if imax < imin:
return None
imid = int(floor((imax + imin)/2))
n = BSTNode(list_in[imid])
print(n.data)
n.left = binary_insert(list_in,imin,imid-1)
n.right = binary_insert(list_in,imid+1,imax)
return n
我總是返回BSTNode
,這是None
只有當輸入二傳手是None
,但樹的唯一節點函數運行後是root
。我懷疑有些東西與我不明白的屬性有關。我很想澄清一下。
> t = BST()
> list_in = [0,5,12]
> t.binary_insert(list_in)
5
0
12
> t.root.data
5
> t.root.left
None
> t.root.right
None
預計:
> t.root.left.data
0
> t.root.right.data
12
您能否澄清您的實際問題是什麼?輸出的哪一部分是你不期望的,你期望它是什麼? – BrenBarn
@BrenBarn:編輯。 – wdonahoe