[leetcode] @python 112. Path Sum

题目链接

https://leetcode.com/problems/path-sum/

题目原文

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

题目大意

给出一棵树和一个整数,是否可以找到一条根到叶子的路径,使得路径上所有节点的和等于该整数

解题思路

递归求解

代码

# 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, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if root == None:
            return False
        if root.left == None and root.right == None:
            return root.val == sum
        return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val) 
原文地址:https://www.cnblogs.com/slurm/p/5272437.html