# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: res,path = [],[] def recur(root,tar): if not root: return path.append(root.val) tar -=root.val if tar==0 and not root.left and not root.right: res.append(list(path)) recur(root.left,tar) recur(root.right,tar) path.pop() recur(root,sum) return res
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: if root == None: return [] res,stack = [],[] def getPath(root,currentSum): stack.append(root.val) currentSum += root.val if (currentSum == sum) and not root.left and not root.right: res.append(list(stack)) if root.left: getPath(root.left,currentSum) if root.right: getPath(root.right,currentSum) stack.pop(-1) getPath(root,0) return res
非递归的方式
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def pathSum(self, root: TreeNode, sum1: int) -> List[List[int]]: result,temp = [],[] def dfs(root, sum1): if root: if not root.right and not root.left: #判断是否为叶节点 temp.append(root.val) b=sum(temp) if b == sum1: result.append(temp[0:]) temp.pop() return temp.append(root.val)# 进栈 dfs(root.left, sum1) dfs(root.right, sum1) temp.pop()# 出栈 dfs(root, sum1) return result