leetcode | Path Sum II

来源:互联网 发布:中国人均粮食产量 知乎 编辑:程序博客网 时间:2024/06/04 23:36

题目:将返回一棵二叉树从根到叶节点所经过的值之和等于Sum的路径。

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5             / \            4   8           /   / \          11  13  4         /  \    / \        7    2  5   1

return

[   [5,4,11,2],   [5,8,4,5]]

思路:

利用递归+深度优先搜索。

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def pathSum(self, root, Sum):        """        :type root: TreeNode        :type sum: int        :rtype: List[List[int]]        """        if not root:            return []        res = []        self.excute(root,[],Sum,res)        return res            def excute(self,root,path,Sum,res):        path.append(root.val)        path_left = path[:]         path_right = path[:]        if not root.left and not root.right: #judge if is a leaf            if Sum-root.val==0:                res.append(path)            return                if root.left:            self.excute(root.left,path_left,Sum-root.val,res)        if root.right:            self.excute(root.right,path_right,Sum-root.val,res)        
代码比较好理解,这里主要讲一下在 excute函数中,为什么每次递归都要拷贝一次path?如下所示:

path_left = path[:] path_right = path[:]
首先看下面代码:

a = [1,2,3]b = aa.append(4)print b#b:[1,2,3,4]
上述代码说明了,如果使用语句 b=a那么,b指向a,所以当修改a时,b也会随之改变。因此,如果我们不使用拷贝path的方法,最后path将储存树中的所有节点。









原创粉丝点击