mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #1961 from ZerenZhang2022/patch-18
Update 0112.路径总和.md
This commit is contained in:
@ -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. 路径总和
|
||||
|
Reference in New Issue
Block a user