[leetcode] 113. Path Sum II @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/87863804

原题

https://leetcode.com/problems/path-sum-ii/

解法1

DFS. Base case是当root为空时, 返回空列表. 定义dfs函数, base case是root为空时, 直接返回. 由于题意要求从根节点到叶子节点, 那么我们判断当root为叶子节点时, 将值加入path, 然后将path加入res.
Time: O(n)
Space: O(1)

代码

# 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]]': 
        def dfs(root, sum, path, res):
            if not root:
                return            
            if root.left is None and root.right is None and root.val == sum:
                path.append(root.val)
                res.append(path)
            dfs(root.left, sum - root.val, path + [root.val], res)
            dfs(root.right, sum - root.val, path + [root.val], res)
            
        res = []
        if not root: return res
        dfs(root, sum, [], res)
        return res

解法2

BFS

代码

# 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 = []
        if not root: return res
        q = [(root, root.val, [root.val])]
        while q:
            node, val, path = q.pop(0)
            if node.left is None and node.right is None and val == sum:                       
                res.append(path)
            if node.left:
                q.append((node.left, val+node.left.val,  path+[node.left.val]))
            if node.right:
                q.append((node.right, val+node.right.val, path+[node.right.val]))
                
        return res

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/87863804