-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathbinary-tree-path-sum.py
37 lines (33 loc) · 1.02 KB
/
binary-tree-path-sum.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
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: the root of binary tree
@param: target: An integer
@return: all valid paths
"""
def binaryTreePathSum(self, root, target):
# write your code here
ret = []
self._binaryTreePathSum(ret, [], root, target)
return ret
def _binaryTreePathSum(self, ret, path, node, target):
if not node:
return
path.append(node.val)
if not (node.left or node.right):
if node.val == target:
ret.append([])
ret[-1].extend(path)
if node.left:
self._binaryTreePathSum(ret, path, node.left, target - node.val)
path.pop()
if node.right:
self._binaryTreePathSum(ret, path, node.right, target - node.val)
path.pop()
# easy: https://www.lintcode.com/problem/binary-tree-path-sum/