📣 黑五价提前开抢|VIP一年通行证5折,蓝莓、Offer多多同步特惠
查看: 1484| 回复: 3
跳转到指定楼层
上一主题 下一主题
收起左侧

[树/链表/图] Binary tree path sum 加不加[:]的区别

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

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,结果半天不对。看了答案发现要加一个[:]。以前依稀听过浅拷贝深拷贝,不知道是不是这里的问题。不知道有没有大神指教一下。

  1. class Solution:
  2.     """
  3.     @param: root: the root of the binary tree
  4.     @param: target: An integer
  5.     @return: all valid paths
  6.     """
  7.     def binaryTreePathSum(self, root, target):
  8.     # Write your code here
  9.     if not root:
  10.       return []
  11.                
  12.     res = []
  13.     path = [root.val]
  14.     self.dfs(root,path,res,target)

  15.     return res
  16.         
  17.     def dfs(self, root, path, res, target):
  18.         
  19.     if not root.left and not root.right:
  20.       if sum(path) == target:
  21.         res.append(path[:])
  22.       return
  23.         
  24.     if root.left:
  25.       path.append(root.left.val)
  26.       self.dfs(root.left,path,res,target)
  27.       path.pop()
  28.         
  29.     if root.right:
  30.       path.append(root.right.val)
  31.       self.dfs(root.right,path,res,target)
  32.       path.pop()
复制代码



如没有[:],就只能保存root的值。比如答案是[[1,2,2],[1,4]],这个错误就会导致输出[[1],[1]] 我可能是缺乏一些基本知识,想了半天不知咋回事。谢谢了

上一篇:长期更新~通过刷题学python3
下一篇:手把手coding教学java和C++
全局:
这个地方比较tricky,path没有[:]时,其实只是append 了path的reference,而非path的值,而且后面的pop()始终在改变path的值。而加了[:](取整个path的值),是把所有的值都append到res了。 你可以理解为前者res是一个reference的list,而后者则是一个list的list。

评分

参与人数 1大米 +3 收起 理由
onlyljy2 + 3 谢谢

查看全部评分

回复

使用道具 举报

🔗
 楼主| onlyljy2 2020-5-4 11:47:55 | 只看该作者
全局:
xgberkeley 发表于 2020-5-4 11:38
这个地方比较tricky,path没有[:]时,其实只是append 了path的reference,而非path的值,而且后面的pop()始 ...

谢谢指点!这下明白了!
回复

使用道具 举报

🔗
dorisH 2020-5-4 14:06:33 | 只看该作者
全局:
也可以用list(path)

评分

参与人数 1大米 +3 收起 理由
onlyljy2 + 3 谢谢

查看全部评分

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表