[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.
题意分析
Input: a binary tree, sum
Output: True or False
Conditions:判断是否存在一条路径,从root-leaf的路径,使得路径的value的和等于sum
题目思路
递归遍历,通过一个不断递减的sum值去判断。
AC代码(Python)
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def hasPathSum(self, root, sum): 10 """ 11 :type root: TreeNode 12 :type sum: int 13 :rtype: bool 14 """ 15 if root == None: 16 return False 17 if root.left == None and root.right == None: 18 return root.val == sum 19 return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val) 20