Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
經典的DFS題目,
重點就是dfs函數中的cur和res參數,利用cur不斷保存當前路徑上的參數,利用res保存符合題目的數組
class Solution(object):
def pathSum(self, root, sum):
if not root:
return []
res = []
self.dfs(root, sum, [], res)
return res
def dfs(self, root, sum, cur, res):
if not root.left and not root.right and sum == root.val:
cur.append(root.val)
res.append(cur)
if root.left:
self.dfs(root.left, sum-root.val, cur+[root.val], res)
if root.right:
self.dfs(root.right, sum-root.val, cur+[root.val], res)