欢迎光临散文网 会员登陆 & 注册

Leetcode Day15 4

2022-04-19 21:17 作者:我喜欢喝一点点  | 我要投稿

剑指 Offer 34. 二叉树中和为某一值的路径

难度中等322

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

示例 1:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22

输出:[[5,4,11,2],[5,8,4,5]]



# Definition for a binary tree node.

# class TreeNode:

#     def __init__(self, val=0, left=None, right=None):

#         self.val = val

#         self.left = left

#         self.right = right

class Solution:

    def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:

        res=[]

        path=[]

        def judgeCur(root,target):

            if not root:return

            path.append(root.val)

            target-=root.val

            if target==0 and not root.left and not root.right:

                tmp=path[:]

                #如果不复制的话,path改变了,res里面的也会改变

                res.append(tmp)

            judgeCur(root.left,target)

            judgeCur(root.right,target)

            path.pop()

        judgeCur(root,target)

        return res



Leetcode Day15 4的评论 (共 条)

分享到微博请遵守国家法律