mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
0112.路径总和 python 113添加迭代法
0112.路径总和 python 113添加迭代法
This commit is contained in:
@ -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. 路径总和
|
||||
|
Reference in New Issue
Block a user