[leetcode] 113. Path Sum II @ python

本文详细解析了LeetCode上路径总和II问题的两种解决方案:深度优先搜索(DFS)与广度优先搜索(BFS)。通过递归与队列实现,找到所有从根节点到叶节点路径,使得路径上的元素之和等于给定的总和。

原题

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值