@@ -10,28 +10,36 @@ def __init__(self, x):
10
10
self .right = None
11
11
class Solution :
12
12
# 返回二维列表,内部每个列表表示找到的路径
13
- def FindPath (self , root , expectNumber ):
14
- if root == None or root . val > expectNumber :
13
+ def FindPath (self , root , sum ):
14
+ if not root :
15
15
return []
16
- elif root .val == expectNumber :
17
- if root . left or root .right :
18
- return [] # 因为路径的定义是从根节点到叶节点所经过的结点, 如果是根结点到任意可到达结点的和为待求值, 可以去掉这个判定
16
+ if root .left == None and root . right == None :
17
+ if sum == root .val :
18
+ return [[ root . val ]]
19
19
else :
20
- return [[expectNumber ]]
21
-
20
+ return []
22
21
stack = []
23
- if root .left :
24
- stackLeft = self .FindPath (root .left , expectNumber - root .val )
25
- for i in stackLeft :
26
- i .insert (0 , root .val )
27
- stack .append (i )
28
- if root .right :
29
- stackRight = self .FindPath (root .right , expectNumber - root .val )
30
- for i in stackRight :
31
- i .insert (0 , root .val )
32
- stack .append (i )
22
+ leftStack = self .pathSum (root .left , sum - root .val )
23
+ for i in leftStack :
24
+ i .insert (0 , root .val )
25
+ stack .append (i )
26
+ rightStack = self .pathSum (root .right , sum - root .val )
27
+ for i in rightStack :
28
+ i .insert (0 , root .val )
29
+ stack .append (i )
33
30
return stack
34
31
32
+ # 优化写法
33
+ def pathSum (self , root , sum ):
34
+ if not root : return []
35
+ if root .left == None and root .right == None :
36
+ if sum == root .val :
37
+ return [[root .val ]]
38
+ else :
39
+ return []
40
+ a = self .pathSum (root .left , sum - root .val ) + self .pathSum (root .right , sum - root .val )
41
+ return [[root .val ] + i for i in a ]
42
+
35
43
pNode1 = TreeNode (10 )
36
44
pNode2 = TreeNode (5 )
37
45
pNode3 = TreeNode (12 )
@@ -46,4 +54,6 @@ def FindPath(self, root, expectNumber):
46
54
47
55
48
56
S = Solution ()
49
- print (S .FindPath (pNode1 , 22 ))
57
+ print (S .FindPath (pNode1 , 22 ))
58
+ # 测试用例:[1,-2,-3,1,3,-2,null,-1] -1
59
+ # 测试用例:[-2, None, -3] -5
0 commit comments