首页 > 解决方案 > 为什么这里的currentPath[-1]会忽略第一个find_paths_recursive(currentNode.left, required_sum - currentNode.val, currentPath, allPaths)?

问题描述

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

def find_paths(root, required_sum):
    allPaths = []
    find_paths_recursive(root, required_sum, [], allPaths)
    return allPaths

def find_paths_recursive(currentNode, required_sum, currentPath, allPaths):
    if currentNode is None:
        return
    currentPath.append(currentNode.val)

    if currentNode.val == required_sum and currentNode.left is None and \
        currentNode.right is None:
        allPaths.append(list(currentPath))
    else:
        find_paths_recursive(currentNode.left, required_sum -
                             currentNode.val, currentPath, allPaths)

        find_paths_recursive(currentNode.right, required_sum -
                             currentNode.val, currentPath, allPaths)
    print("currentPath ", currentPath)
    print("currpath", currentPath[-1])
    del currentPath[-1]      #HERE <-------- 




def main():

    root = TreeNode(12)
    root.left = TreeNode(7)
    root.right = TreeNode(1)
    root.left.left = TreeNode(4)
    root.right.left = TreeNode(10)
    root.right.right = TreeNode(5)
    sum = 24
    print("Tree paths with sum " + str(sum) +
          ": " + str(find_paths(root, sum)))


main()

打印语句是为了查看这段代码在做什么。此代码转到 [12, 1, 10] ,这是我得到的结尾。之后,我们执行 del currentPath[-1] 删除 10,但这不就是转到 currentNode.left 递归函数吗?为什么它跳过 currentNode.left 并转到 currentNode.right 转到 [12, 1, 5] ?

标签: pythonpython-3.xrecursion

解决方案


推荐阅读