题目来源:
https://leetcode.com/problems/path-sum/
题意分析:
给出一个树和一个整数,判断这棵树是否有一条从根到叶节点的路径,使得路径之和为给定的整数。
题目思路:
这题还是用递归的思想。如果根节点的左右子树都为空,那么返回根的值是否等于sum,否者,sum 减去根的值得到一个newsum,判断newsum在左子树或者右子树是否有路径。
代码(python):
# 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 if root.left == None: return self.hasPathSum(root.right,sum - root.val) if root.right == None: return self.hasPathSum(root.left,sum - root.val) return self.hasPathSum(root.left,sum - root.val) or self.hasPathSum(root.right,sum - root.val)