题解 | #二叉树中和为某一值的路径(一)# 笨办法

二叉树中和为某一值的路径(一)

https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c

from typing import List

class Solution:
    def hasPathSum(self , root: TreeNode, sum: int) -> bool:
        # write code here     
        possibles = self.getSum(root)
        print(possibles)        
        return sum in possibles

    def getSum(self, root: TreeNode) -> List[int]:
        if not root:
            return []

        result: List[int] = []

        if root.left or root.right:
            if root.left:          
                left_possibles = self.getSum(root.left)
                for i in left_possibles:                
                    result.append(i + root.val) 
            if root.right:
                right_possibles = self.getSum(root.right)
                for i in right_possibles:                
                    result.append(i + root.val)
        else:
            result.append(root.val)
             
        return result

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务