最终目标是将节点从一个树复制到另一个树。我想访问二叉树中的每个节点,并在经过多次遍历后返回一个节点实例。我似乎无法弄清楚如何返回特定节点。每次返回的节点都匹配根节点的id,因为我将根节点传递给函数。
class node():
def __init__(self):
self.parent = None
self.left = None
self.right = None
def randnode(self, target):
global count
if target == count:
# print 'At target', '.'*25, target
return self
else:
if self.left is not None:
count += 1
self.left.randnode(target)
if self.right is not None:
count += 1
self.right.randnode(target)
答案 0 :(得分:0)
如果你正在进行DFS并计算迭代次数,你甚至不需要递归,只需要尝试一堆地方,然后弹出/推送数据。
def dfs(self,target):
count = 0
stack = [start]
while stack:
node = stack.pop()
if count == target:
return node
if node is None: # since we push left/right even if None
continue # stop pushing after we hit None node
stack.extend([self.left,self.right])
return -1 # ran out of nodes before count
加分点:将堆栈交换为BFS队列
除此之外,您可能希望将计数作为参数传递,就像所有自尊的递归调用一样,您可以使此无状态; - )
class node():
def __init__(self):
self.parent = None
self.left = None
self.right = None
def randnode(self, target,count=0):
if target == count:
# print 'At target', '.'*25, target
return self
if self.left is not None:
return self.left.randnode(target,count + 1)
if self.right is not None:
return self.right.randnode(target,count + 1)