题目
思路
递归
代码
# 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 pathSum(self, root, sum, num):
if not root: return False
if not root.left and not root.right:
return root.val + num == sum
return self.pathSum(root.left, sum, num + root.val) or self.pathSum(root.right, sum, num + root.val)
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
return self.pathSum(root, sum, 0)