112. 路径总和

112. 路径总和_第1张图片

思路:
找到递归结束的判决条件:
 if not root:
            return False   
        if not root.left and not root.right and root.val == s:
            return True

代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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

你可能感兴趣的:(Leetcode)