@@ -10,28 +10,36 @@ def __init__(self, x):
1010 self .right = None
1111class Solution :
1212 # 返回二维列表,内部每个列表表示找到的路径
13- def FindPath (self , root , expectNumber ):
14- if root == None or root . val > expectNumber :
13+ def FindPath (self , root , sum ):
14+ if not root :
1515 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 ]]
1919 else :
20- return [[expectNumber ]]
21-
20+ return []
2221 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 )
3330 return stack
3431
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+
3543pNode1 = TreeNode (10 )
3644pNode2 = TreeNode (5 )
3745pNode3 = TreeNode (12 )
@@ -46,4 +54,6 @@ def FindPath(self, root, expectNumber):
4654
4755
4856S = 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