牛客——二叉树根节点到叶节点和为指定的数路径
发布日期:2021-05-06 11:08:00 浏览次数:19 分类:原创文章

本文共 1258 字,大约阅读时间需要 4 分钟。

在这里插入图片描述
在这里插入图片描述


# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = None## # @param root TreeNode类 # @param sum int整型 # @return int整型二维数组## class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = None## # @param root TreeNode类 # @param sum int整型 # @return int整型二维数组#class Solution:    def pathSum(self , root , target):        # write code here        def dfs(root, sub_res):            if root is None:                return            if root.left is None and root.right is None:                sub_res.append(root.val)                if sum(sub_res) == target:                    res.append(sub_res[:])                return            else:                sub_res.append(root.val)                if root.left:                    dfs(root.left, sub_res)                    sub_res.pop()                if root.right:                    dfs(root.right, sub_res)                    sub_res.pop()                        res = []        if root is None:            return res                if root.left is None and root.right is None and root.val == target:            res.append([root.val])            return res        dfs(root, [])        return res
上一篇:牛客——链表指定区间翻转
下一篇:最小编辑代价(牛客)

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2025年04月09日 07时42分33秒