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

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

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

思路:

1、深度优先遍历整个树dfs,每遍历一个节点,sum减去当前节点的val

2、如果到达叶子节点(左右子树均为空),sum为0,则说明该路径满足条件,返回True

3、如果遍历到最后,也每返回True,说明不存在满足条件节点,返回False

# class TreeNode:

class Solution:
    def hasPathSum(self , root: TreeNode, sum: int) -> bool:
        # dfs
        if not root:
            return False
        
        return self.dfs(root, sum)
        
    
    def dfs(self, root, sum):
        
        if not root:
            return False
        
        sum -= root.val
        if not root.left and not root.right and sum == 0:
            return True
        
        return self.dfs(root.left, sum) or self.dfs(root.right, sum)
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务