python - 为什么这里的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] ?
解决方案
推荐阅读
- java - 我的 java exe 无法连接到 sql 数据库,但如果我使用我的 IDE,它可以工作
- intellij-idea - 子项目中对包的未解决依赖关系
- r - 计算动态日期时间范围内每个组的观察值
- css - Bootstrap3 - 在小型设备上将按钮划分为 2 行
- laravel - Vue组件中如何使用Laravel数据
- .net - 对 SOAP 服务的无效请求不会产生预期的 SOAP 错误
- java - 为什么我的总价格应该是 11 时打印为 0.0
- macros - Rust 宏:如何创建派生标识符?
- javascript - 如何在没有 html 的情况下将 css 文件包含到 svg 文件中
- javascript - 如何使用带有滚动搜索和分页选项的动态标题制作 bootstrap4 数据表