注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
本帖最后由 onlyljy2 于 2020-5-4 11:18 编辑
**求助一下,半天想不明白。先做了一道Lintcode 480 Binary tree paths (https://www.lintcode.com/problem/binary-tree-paths/description), 然后接着刷了一道376 Binary tree path sum (https://www.lintcode.com/problem/binary-tree-path-sum/description). 因为基本上是一个题目,我就加了一个if条件筛选出符合条件的path,结果半天不对。看了答案发现要加一个[:]。以前依稀听过浅拷贝深拷贝,不知道是不是这里的问题。不知道有没有大神指教一下。
- class Solution:
- """
- @param: root: the root of the binary tree
- @param: target: An integer
- @return: all valid paths
- """
- def binaryTreePathSum(self, root, target):
- # Write your code here
- if not root:
- return []
-
- res = []
- path = [root.val]
- self.dfs(root,path,res,target)
- return res
-
- def dfs(self, root, path, res, target):
-
- if not root.left and not root.right:
- if sum(path) == target:
- res.append(path[:])
- return
-
- if root.left:
- path.append(root.left.val)
- self.dfs(root.left,path,res,target)
- path.pop()
-
- if root.right:
- path.append(root.right.val)
- self.dfs(root.right,path,res,target)
- path.pop()
复制代码
如没有[:],就只能保存root的值。比如答案是[[1,2,2],[1,4]],这个错误就会导致输出[[1],[1]] 我可能是缺乏一些基本知识,想了半天不知咋回事。谢谢了
|