path sum

又是一道divide and conquer的题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class (object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
return self.helper(root, 0, sum)
def helper(self, root, cur, sum):
if not root:
return False
cur += root.val
if not root.left and not root.right and cur == sum:
return True
return self.helper(root.left, cur, sum) or self.helper(root.right, cur, sum)