113. Path Sum II

2017-11-11  本文已影响0人  xiaoyaook

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)
上一篇下一篇

猜你喜欢

热点阅读