112.二叉树是否存在路径总和等于目标值

思路:深度优先遍历

注意:路径指根节点到叶子节点,叶子节点是没有子节点的节点

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root:
            return False
        self.res = False
        def dfs(root,sum):
            if not root:
                return
            sum = sum -root.val
            #print sum
            if not root.left and not root.right:
                if sum == 0:
                    self.res = True
                return
            dfs(root.left,sum)
            dfs(root.right,sum)
        dfs(root,sum)
        return self.res

你可能感兴趣的:(112.二叉树是否存在路径总和等于目标值)