Merge pull request #1961 from ZerenZhang2022/patch-18

Update 0112.路径总和.md
This commit is contained in:
程序员Carl
2023-03-30 10:59:00 +08:00
committed by GitHub

View File

@ -560,6 +560,26 @@ class Solution:
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
### 112. 路径总和