鍍金池/ 問(wèn)答/Python/ 關(guān)于二叉樹的一道簡(jiǎn)單算法題,結(jié)果很詭異(python)

關(guān)于二叉樹的一道簡(jiǎn)單算法題,結(jié)果很詭異(python)

lintcode原題:
二叉樹的路徑和
給定一個(gè)二叉樹,找出所有路徑中各節(jié)點(diǎn)相加總和等于給定 目標(biāo)值 的路徑。
一個(gè)有效的路徑,指的是從根節(jié)點(diǎn)到葉節(jié)點(diǎn)的路徑。
我的解答

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


class Solution:
    """
    @param: root: the root of binary tree
    @param: target: An integer
    @return: all valid paths
    """
    def binaryTreePathSum(self, root, target):
        # write your code here
        result=[]
        path=[]
        self.dfs(root,path,result,target)
        return result
        
        
        
    def dfs(self,root,path,result,target):
        if root is None:
            return
        path.append(root.val)
        if  root.left is None and  root.right is None and sum(path)==target:
            result.append(path)
        if root.left:
            self.dfs(root.left,path,result,target)
        if root.right:
            self.dfs(root.right,path,result,target)
        path.pop()
            

結(jié)果總是錯(cuò)誤
輸入
{1,2,4,2,3}
5
輸出
[[],[]]
期望答案
[[1,2,2],[1,4]]

我實(shí)在想不通為什么答案是空,后來(lái)我意識(shí)到可能是傳參數(shù)的問(wèn)題,改成如下代碼:

if  root.left is None and  root.right is None and sum(path)==target:
            result.append(path+[])

這里只改了中間那一行,將path改為path+[],居然華麗麗的成功了,實(shí)在是想不通為什么,有人指點(diǎn)一二嗎?謝了!

回答
編輯回答
心沉
result.append(copy.copy(path)) # 新建一個(gè)list,否則你存的只是path的地址,path增加數(shù)據(jù),result也會(huì)增加
path + [] 等效于新建了一個(gè)list

>>> a = [1]
>>> id(a) == id(a + [])
False
>>> id(a) == id(a)
True
>>>

2017年6月8日 18:55