[leetcode]Path Sum II @ Python

原题地址:https://oj.leetcode.com/problems/path-sum-ii/

题意:

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]
]

解题思路:这题需要将根到叶子的路径和为sum的路径都枚举出来。一样是使用递归。

代码:

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @param sum, an integer
    # @return a list of lists of integers
    def pathSum(self, root, sum):
        def dfs(root, currsum, valuelist):
            if root.left==None and root.right==None:
                if currsum==sum: res.append(valuelist)
            if root.left:
                dfs(root.left, currsum+root.left.val, valuelist+[root.left.val])
            if root.right:
                dfs(root.right, currsum+root.right.val, valuelist+[root.right.val])
        
        res=[]
        if root==None: return []
        dfs(root, root.val, [root.val])
        return res

 

posted @ 2014-05-26 10:11  南郭子綦  阅读(3283)  评论(0编辑  收藏  举报