forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
60 lines (49 loc) · 1.53 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Given a binary tree, find the path sum that matches
# the target value
'''
Created on May 14, 2013
@author: Yubin Bai
'''
class Node:
val = left = right = None
def __init__(self, val=None):
self.val = val
def generateTreeFromArray(val):
def generateTreeHelper(val, root):
if root < len(val):
r = Node(val[root])
r.left = generateTreeHelper(val, 2 * root + 1)
r.right = generateTreeHelper(val, 2 * root + 2)
return r
else:
return None
return generateTreeHelper(val, 0)
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
def pathSumHelper(root, sum):
if root.left == None and root.right == None:
if sum == root.val:
path.append(root.val)
results.append(list(path))
path.pop()
return
path.append(root.val)
if root.left != None:
pathSumHelper(root.left, sum - root.val)
if root.right != None:
pathSumHelper(root.right, sum - root.val)
path.pop()
if root == None:
return False
results = []
path = []
pathSumHelper(root, sum)
return len(results) > 0
if __name__ == '__main__':
val = [5, 4, 8, 11, 0, 13, 4, 7, 2, 0, 0, 0, 0, 5, 1]
tree = generateTreeFromArray(val)
s = Solution()
print s.hasPathSum(tree, 22)