# 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, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ if not root: return [] res=[] self.DFS(root,sum,[root.val],res) return res def DFS(self,root,value,arr,res): if not root: return if sum(arr)==value and not root.left and not root.right: res.append(arr) return if root.left: self.DFS(root.left,value,arr+[root.left.val],res) if root.right: self.DFS(root.right,value,arr+[root.right.val],res) # # 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, sum): # """ # :type root: TreeNode # :type sum: int # :rtype: List[List[int]] # """ # if not root: return [] # res = [] # self.dfs(root, sum, res, [root.val]) # return res # # def dfs(self, root, target, res, path): # if not root: return # if sum(path) == target and not root.left and not root.right: # res.append(path) # return # if root.left: # self.dfs(root.left, target, res, path + [root.left.val]) # if root.right: # self.dfs(root.right, target, res, path + [root.right.val]) solu=Solution() root=TreeNode(5) root.left=TreeNode(4) root.right=TreeNode(8) root.left.left=TreeNode(11) root.right.left=TreeNode(13) root.right.right=TreeNode(4) root.left.left.left=TreeNode(7) root.left.left.right=TreeNode(2) root.right.right.left=TreeNode(5) root.right.right.right=TreeNode(1) sum1=22 print(solu.pathSum(root,sum1))