@@ -496,25 +496,20 @@ class solution:
496
496
def pathsum (self , root : treenode, targetsum : int ) -> list[list[int ]]:
497
497
498
498
def traversal (cur_node , remain ):
499
- if not cur_node.left and not cur_node.right and remain == 0 :
500
- result.append(path[:])
501
- return
502
-
503
- if not cur_node.left and not cur_node.right: return
499
+ if not cur_node.left and not cur_node.right:
500
+ if remain == 0 :
501
+ result.append(path[:])
502
+ return
504
503
505
504
if cur_node.left:
506
505
path.append(cur_node.left.val)
507
- remain -= cur_node.left.val
508
- traversal(cur_node.left, remain)
506
+ traversal(cur_node.left, remain- cur_node.left.val)
509
507
path.pop()
510
- remain += cur_node.left.val
511
508
512
509
if cur_node.right:
513
510
path.append(cur_node.right.val)
514
- remain -= cur_node.right.val
515
- traversal(cur_node.right, remain)
511
+ traversal(cur_node.right, remain- cur_node.left.val)
516
512
path.pop()
517
- remain += cur_node.right.val
518
513
519
514
result, path = [], []
520
515
if not root:
@@ -524,6 +519,30 @@ class solution:
524
519
return result
525
520
```
526
521
522
+ ** 迭代法,用第二个队列保存目前的总和与路径**
523
+ ``` python
524
+ class Solution :
525
+ def pathSum (self , root : Optional[TreeNode], targetSum : int ) -> List[List[int ]]:
526
+ if not root:
527
+ return []
528
+ que, temp = deque([root]), deque([(root.val, [root.val])])
529
+ result = []
530
+ while que:
531
+ for _ in range (len (que)):
532
+ node = que.popleft()
533
+ value, path = temp.popleft()
534
+ if (not node.left) and (not node.right):
535
+ if value == targetSum:
536
+ result.append(path)
537
+ if node.left:
538
+ que.append(node.left)
539
+ temp.append((node.left.val+ value, path+ [node.left.val]))
540
+ if node.right:
541
+ que.append(node.right)
542
+ temp.append((node.right.val+ value, path+ [node.right.val]))
543
+ return result
544
+ ```
545
+
527
546
## go
528
547
529
548
112 . 路径总和
0 commit comments