0112.路径总和 python 113添加迭代法

0112.路径总和 python 113添加迭代法
This commit is contained in:
SianXiaoCHN
2022-03-25 20:35:54 -05:00
parent f8392906ac
commit be6cb9f130

View File

@ -519,6 +519,30 @@ class solution:
return result
```
**迭代法,用第二个队列保存目前的总和与路径**
```python
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root:
return []
que, temp = deque([root]), deque([(root.val, [root.val])])
result = []
while que:
for _ in range(len(que)):
node = que.popleft()
value, path = temp.popleft()
if (not node.left) and (not node.right):
if value == targetSum:
result.append(path)
if node.left:
que.append(node.left)
temp.append((node.left.val+value, path+[node.left.val]))
if node.right:
que.append(node.right)
temp.append((node.right.val+value, path+[node.right.val]))
return result
```
## go
112. 路径总和