Update 0112.路径总和.md

增加:0113 - python - 迭代法 - 前序遍历解法
This commit is contained in:
ZerenZhang2022
2023-03-18 16:34:16 -04:00
committed by GitHub
parent b81b392ed0
commit 87dbf5efc5

View File

@ -560,6 +560,26 @@ class Solution:
return result return result
``` ```
**迭代法,前序遍历**
```python
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root: return []
stack, path_stack,result = [[root,root.val]],[[root.val]],[]
while stack:
cur,cursum = stack.pop()
path = path_stack.pop()
if cur.left==cur.right==None:
if cursum==targetSum: result.append(path)
if cur.right:
stack.append([cur.right,cursum+cur.right.val])
path_stack.append(path+[cur.right.val])
if cur.left:
stack.append([cur.left,cursum+cur.left.val])
path_stack.append(path+[cur.left.val])
return result
```
## go ## go
### 112. 路径总和 ### 112. 路径总和