Python DFS实现在两个树节点之间查找路由

Python DFS实现在两个树节点之间查找路由,python,tree,depth-first-search,path-finding,Python,Tree,Depth First Search,Path Finding,我不确定这种实现有什么问题。我试图找到节点1和目标节点之间的路由,值为11。正确的ans应为[1,2,4,11]。但是它返回:[1,2,4,11,5,3]让我们仔细看看下面的代码行: class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def getDFSpath(root,goal,stack):

我不确定这种实现有什么问题。我试图找到节点1和目标节点之间的路由,值为11。正确的ans应为[1,2,4,11]。但是它返回:[1,2,4,11,5,3]

让我们仔细看看下面的代码行:

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def getDFSpath(root,goal,stack):
    stack.append(root.val)
    if root.left is None and root.right is None and root.val != goal:
        stack.pop()
        return []
    elif root.val == goal:
        return stack
    else:
        leftstack = getDFSpath(root.left,goal,stack)
        rightstack = getDFSpath(root.right,goal,stack)
        if len(leftstack) == 0 and len(rightstack) > 0:
            return rightstack
        elif len(rightstack) == 0 and len(leftstack) > 0:
            return leftstack
        else:
            return []

one = TreeNode(1)
two =TreeNode(2)
three =TreeNode(3)
four = TreeNode(4)
five =TreeNode(5)
six =TreeNode(6)
seven =TreeNode(7)
eight = TreeNode(8)
nine =TreeNode(9)
ten = TreeNode(10)
eleven = TreeNode(11)

one.left = two
one.right = three
two.left = four
two.right = five
three.left = six
three.right = seven
four.left = ten
four.right = eleven
five.left = nine
five.right = eight
mystack = getDFSpath(one,11,[])
print(mystack)
在这里,您为左节点和右节点调用DFS,并传递相同的
堆栈
变量。例如,调用左节点的DFS会找到一个路径(简单的示例-从1到2的路由)。之后,您为右节点(3)调用DFS。当您使用相同的stack`变量时,为右节点调用DFS将修改它。请看下面一行:

leftstack = getDFSpath(root.left,goal,stack)
rightstack = getDFSpath(root.right,goal,stack)
对于节点3,它不是真的,所以它不会从堆栈中删除3!您将得到
[1,2,3]
。此外,当节点只有左或右子节点时,也不会处理这种情况。修复了带有我的注释的代码:

if root.left is None and root.right is None and root.val != goal:
输出:

[1,2,4,11]

def getDFSpath(root, goal, stack):
    stack.append(root.val)
    if root.val == goal:
        return stack
    else:
        leftstack = getDFSpath(root.left, goal, stack[:]) if root.left is not None else []  # if left node is missing skip it
        rightstack = getDFSpath(root.right, goal, stack[:]) if root.right is not None else []  # if right node is missing skip it
        if len(leftstack) == 0 and len(rightstack) > 0:
            return rightstack
        elif len(rightstack) == 0 and len(leftstack) > 0:
            return leftstack
        else:
            stack.pop()  # we didn't find path, remove current node from stack
            return []