2015-10-14 128 views
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) 
+1

首先,你需要返回递归调用的结果。 '返回self.left.randnode(target)'和'self.right.randnode(target)'。您可能还希望在递归时检查[此答案](http://stackoverflow.com/a/30214677/1903116)。 – thefourtheye

+0

您可以添加您的示例数据+调用此函数来尝试可能的解决方案吗? – Jiby

回答

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)