1. 程式人生 > >LeetCode 113. 路徑總和 II Python

LeetCode 113. 路徑總和 II Python

給定一個二叉樹和一個目標和,找到所有從根節點到葉子節點路徑總和等於給定目標和的路徑。

說明: 葉子節點是指沒有子節點的節點。

示例:
給定如下二叉樹,以及目標和 sum = 22

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

返回:

[
   [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 = None

class Solution(object):
    def pathSum(self, root, sum1):
        res = []
        if not root: return []
        def dfs(root,path,mysum,sum1,res):
            if mysum == sum1 and not root.left and not root.right:
                res.append(path)
                return
            
            if root.left:
                dfs(root.left,path+[root.left.val],mysum+root.left.val,sum1,res)
            if root.right:
                dfs(root.right,path+[root.right.val],mysum+root.right.val,sum1,res)
        dfs(root,[root.val],root.val,sum1,res)
        return res