返回

深度优先搜索DFS(二)从根节点到叶子节点路径等于targetSum的路径

闲谈

LeetCode 113. 路径总和 II 题意:给出一棵二叉树,给定一个目标数值 targetSum,输出所有从根节点到叶子节点路径数值和与 targetSum 相等的路径。

思路:遍历所有路径,可以使用深度优先搜索(DFS)来实现。从根节点开始,依次遍历左子树和右子树,并将当前节点的值加入到路径中。如果当前节点是叶子节点,并且路径中的数值和等于 targetSum,则将路径加入到结果集中。

def pathSum(root, targetSum):
    """
    :type root: TreeNode
    :type targetSum: int
    :rtype: List[List[int]]
    """
    res = []
    path = []

    def dfs(root, target):
        if not root:
            return

        path.append(root.val)
        target -= root.val

        if not root.left and not root.right and target == 0:
            res.append(path.copy())

        dfs(root.left, target)
        dfs(root.right, target)

        path.pop()

    dfs(root, targetSum)
    return res

举个例子,给定一棵二叉树,其中:

        5
       / \
      4   8
     /   / \
    11  13  4
   /  \    / \
  7    2  5   1

目标值 targetSum = 22

路径 5-4-11-2 就是一条从根节点到叶子节点路径数值和与 targetSum 相等的路径。

实现代码:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def pathSum(root, targetSum):
    """
    :type root: TreeNode
    :type targetSum: int
    :rtype: List[List[int]]
    """
    res = []
    path = []

    def dfs(root, target):
        if not root:
            return

        path.append(root.val)
        target -= root.val

        if not root.left and not root.right and target == 0:
            res.append(path.copy())

        dfs(root.left, target)
        dfs(root.right, target)

        path.pop()

    dfs(root, targetSum)
    return res

# 测试用例
root = TreeNode(5)
root.left = TreeNode(4)
root.right = TreeNode(8)
root.left.left = TreeNode(11)
root.left.left.left = TreeNode(7)
root.left.left.right = TreeNode(2)
root.right.left = TreeNode(13)
root.right.right = TreeNode(4)
root.right.right.left = TreeNode(5)
root.right.right.right = TreeNode(1)

targetSum = 22
result = pathSum(root, targetSum)
print(result)

输出结果:

[[5, 4, 11, 2], [5, 8, 4, 5]]