1
返回特定點的最近點後,下一次當我返回最近點到另一點時,返回與之前相同的最近點。這是爲什麼?最近的點等於樹中的整個不同的地方爲什麼?
class kdnode:
def __init__(self,point,left,right):
self.point = point
self.left = left
self.right = right
class kdTree:
def __init__(self,points,threshold):
self.threshold = threshold
self.root = self.make_kdtree(points)
self.froot = None
self.isFirst = True
def make_kdtree(self,points,depth = 0):
if(len(points) <= self.threshold):
return kdnode(points,None,None)
dimension = 2
axis = depth % dimension
sp = sorted(points,key = lambda point:point[axis])
mid = len(points)//2
return kdnode(sp[mid],self.make_kdtree(sp[:mid],depth+1),self.make_kdtree(sp[mid+1:],depth+1))
def find_closest(self,point,depth=0):
if self.isFirst:
self.froot = self.root.point
self.isFirst = False
if(self.root.left) is None and self.root.right is None:
return self.root.point
axis = depth%2
if point[axis] > self.root.point[axis]:
self.root = self.root.right
else:
self.root = self.root.left
return self.find_closest(point,depth+1)
謝謝。但你能更清楚地解釋一下嗎? –
'self'是當前對象。 'self.isFirst = False'改變當前對象。下次調用find_closest()時它不會一樣,因爲你改變了它。 – remram