0
最终目标是将节点从一棵树复制到另一棵树。我想访问二叉树中的每个节点并在多次遍历后返回一个节点实例。我似乎无法弄清楚如何返回一个特定的节点。每次返回的节点都匹配根节点的ID时,我将根节点传递给该函数。在Python中遍历n遍历树并返回节点实例
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)
首先,你需要返回递归调用的结果。 '返回self.left.randnode(target)'和'self.right.randnode(target)'。您可能还希望在递归时检查[此答案](http://stackoverflow.com/a/30214677/1903116)。 – thefourtheye
您可以添加您的示例数据+调用此函数来尝试可能的解决方案吗? – Jiby